AttributeError: '模块'对象没有属性'ToManyFields

0 投票
1 回答
605 浏览
提问于 2025-05-01 13:58

我创建了一个基础资源(BaseResource)。

class BaseResource(ModelResource):

    def wrap_view(self, view):

        @csrf_exempt
        def wrapper(request, *args, **kwargs):
            try:
                callback = getattr(self, view)
                return callback(request, *args, **kwargs)
            except IntegrityError, e:

                return HttpResponse(e, status=300,
                                    reason='Internal Server error')

        return wrapper

    class Meta:

        allowed_methods = ['get', 'post', 'put']
        list_allowed_methods = ['get', 'post', 'put']
        detail_allowed_methods = ['get', 'post', 'put']
        include_resource_uri = False
        default_format = 'application/json'
        always_return_data = True
        throttle = BaseThrottle(throttle_at=3, timeframe=10,
                                expiration=1)
        authentication = MultiAuthentication(SessionAuthentication(),
                ApiKeyAuthentication())
        authorization = Authorization()
        serializer = urlencodeSerializer()

这是我的资源:

class UserResource(BaseResource):

     groups = fields.ToManyFields('GroupResource', 'group')

    class Meta:

        queryset = User.objects.all()
        resource_name = 'user'
        excludes = ['password']
        authorization = Authorization()
        allowed_methods = ['get', 'post', 'put']
        filtering = {'username': ALL, 'email': ALL}


class GroupResource(BaseResource):

    user = fields.ForeignKey(UserResource, 'user') 
    permissions = fields.ToManyFields('PermissionResource','permissions_set', related_name='permission')

    class Meta:

        queryset = Group.objects.all()
        allowed_methods = ['get', 'post', 'put']
        resource_name = 'group'

class PermissionResource(BaseResource):

    group = fields.ToOneField('GroupResource', 'group_set') 

    class Meta:

        queryset = Permission.objects.all()
        allowed_methods = ['get']

我想为用户创建一个资源,这个资源是基于基础资源(BaseResource)扩展的。但是当我建立关系时,出现了以下错误:

groups = fields.ToManyFields('GroupResource', 'group')
AttributeError: 'module' object has no attribute 'ToManyFields'

我搜索过了,但找不到能帮助我的信息。有没有什么线索?我哪里做错了?任何建议都欢迎。谢谢!

暂无标签

1 个回答

3

这个 AttributeError 错误信息直接告诉你出了什么问题:

关于你的组资源:

class GroupResource(BaseResource):

    user = fields.ForeignKey(UserResource, 'user') 
    permissions = fields.ToManyFields('PermissionResource','permissions_set', related_name='permission')

你在使用 ToManyFields,但在 GroupResource 中并没有定义这个东西。这意味着它必须来自一个父类,而这个父类从 BaseResource 开始(在这里没有定义),还有 ModelResource,不过这里没有贴出来。

虽然你可以去调试,看看这个方法到底在哪里定义,但看起来你想用的字段在 Django 的文档中并没有,而是在 TastyPie 的文档中。

你似乎有个拼写错误。Django-TastyPie 的字段其实叫做 ToManyField

撰写回答