2015-08-26 49 views
1

我有以下用戶資源代碼,如何插入'permissions field',它返回用戶的權限列表?如何在用戶資源中插入user_permissions字段?

class UserResource(ModelResource): 
    user_permissions = fields.ToManyField #?????? 
    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'user' 
     authorization = Authorization() 
     always_return_data = True 
     list_allowed_methods = ['get', 'post', 'put', 'delete'] 
     authorization = DjangoAuthorization() 
     authentication = MultiAuthentication(BasicAuthentication(), SessionAuthentication()) 
     filtering = { 
      "date_joined": ALL, 
      "email": ALL, 
      "first_name": ALL, 
      "is_active": ALL, 
      "is_staff": ALL, 
      "is_superuser": ALL, 
      "last_login": ALL, 
      "last_name": ALL, 
      "username": ALL, 
      "user_permissions": ALL_WITH_RELATIONS, 
    } 

回答

2

如果您使用的是django-tastypie,它可以在沒有字段的情況下像這樣工作。

class UserResource(ModelResource): 
    class Meta: 
     # your definitions 

    def dehydrate(self, bundle): 
     # Include user permissions 
     bundle.data['user_permissions'] = bundle.obj.user_permissions() 
     return bundle 
1

我發現這個解決方案:

class PermissionResource(ModelResource): 

    class Meta: 
     queryset = Permission.objects.all() 

     resource_name = 'permission' 
     authorization = Authorization() 
     always_return_data = True 
     list_allowed_methods = ['get', 'post', 'put', 'delete'] 
     authorization = DjangoAuthorization() 
     authentication = MultiAuthentication(BasicAuthentication(), SessionAuthentication()) 

class UserResource(ModelResource): 
    user_permissions = fields.ToManyField(PermissionResource,'user_permissions',null=True,full=True) 

    class Meta: 
     queryset = User.objects.all() 
     resource_name = 'user' 
     authorization = Authorization() 
     always_return_data = True 
     list_allowed_methods = ['get', 'post', 'put', 'delete'] 
     authorization = DjangoAuthorization() 
     authentication = MultiAuthentication(BasicAuthentication(), SessionAuthentication()) 
     filtering = { 
      "date_joined": ALL, 
      "email": ALL, 
      "first_name": ALL, 
      "is_active": ALL, 
      "is_staff": ALL, 
      "is_superuser": ALL, 
      "last_login": ALL, 
      "last_name": ALL, 
      "username": ALL, 
      "user_permissions": ALL_WITH_RELATIONS, 

     } 
相關問題