按tastypie中的用户组筛选用户

时间:2014-09-10 19:08:10

标签: tastypie

这是我的用户资源类

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['get', 'post', 'put', 'patch']
        resource_name = 'user'
        excludes = ['password']
        #authentication = SessionAuthentication()
        #authorization = DjangoAuthorization()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'id': ALL,
            'username': ALL,
            'groups': ALL_WITH_RELATIONS
        }

我想按组名过滤用户。 比如/ api / v1 / user /?format = json& groups__name = group_name

以上格式不起作用。如何在get请求中过滤它?

1 个答案:

答案 0 :(得分:2)

您必须将要使用的模型中的关系字段添加到资源中。首先,您必须为组模型创建模型资源。然后在UserResource中创建链接到GroupResource的To Many字段。

这样的事情:

class GroupResource(ModelResource):
    class Meta:
        queryset = Group.objects.all()
        resource_name = 'group'
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'id': ALL,
            'name': ALL,
        }


class UserResource(ModelResource):
    groups = fields.ToManyField(GroupResource, 'groups',
                                blank=True)
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['get', 'post', 'put', 'patch']
        resource_name = 'user'
        excludes = ['password']
        #authentication = SessionAuthentication()
        #authorization = DjangoAuthorization()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'id': ALL,
            'username': ALL,
            'groups': ALL_WITH_RELATIONS
        }

原因是Tastypie必须知道关系对象授权,身份验证,resource_name和其他无法填充的设置。