0

我有 2 个由外键链接的资源

我想在创建/修改 AJob 时将 AUser 资源设为只读

class AUser(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        authentication = SessionAuthentication()
        authorization = Authorization()
        excludes = ['email', 'password', 'is_superuser', 'is_staff', 'is_active', 'date_joined', 'last_login']
    def can_update(self):
        return False  
    def can_create(self):
        return False
    def can_delete(self):
        return False
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

class AJob(ModelResource):
    user = fields.ForeignKey( AUser, 'user', full=True)
    paused = fields.BooleanField(attribute='isPaused', readonly=True)
    hasRules = fields.BooleanField(attribute='hasRules', readonly=True)
    class Meta:
        queryset = Job.objects.all()
        resource_name = 'job'
        authentication = SessionAuthentication()
        api_name = 'v1'
        authorization = Authorization()
        allowed_methods = ['get', 'post', 'delete']

    def obj_create(self, bundle, request=None, **kwargs):
        return super(AJob, self).obj_create(bundle, request, user=request.user)

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)

我尝试将 readonly=True 直接添加到 foreignKey 中,但是在补水时它会被忽略并违反约束,因为 user 是 null

如果在我的 POST AJob 请求中我追加

"用户":{"id":"5","is_staff":false}

5 是当前用户

用户模型得到更新,删除管理员角色

似乎做 save_related 时的美味派没有检查任何授权

如何将此用户资源设置为只读?

我正在使用tastepie v0.9.12-alpha

4

1 回答 1

2

您可以修改资源save_related内部的方法AJob并将其定义为不修改AUser. 您可以根据需要将 ForeignKey 定义为只读,但是您必须提供dehydrate_user方法并在内部获取要返回的值。这将是类似的东西return bundle['data'].user

于 2012-09-24T09:07:30.660 回答