2014-09-10 41 views
1

这是我的用户资源类过滤器用户通过用户组中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 
     } 

我想通过自己的组名来过滤用户。 Like/api/v1/user /?format = json & groups__name = group_name

上述格式不起作用。我如何在获取请求中过滤它?

回答

2

您必须将您要使用的关系字段添加到资源中。首先,您必须为组模型创建模型资源。然后在链接到GroupResource的UserResource中创建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和休息一堆无法填充自身设置。