Tastypie,如何防止对由外键链接的资源进行修改

时间:2012-09-23 16:59:08

标签: django tastypie

我有2个由foreignKey链接的资源

我想在创建/修改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":假}

5是当前用户

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

执行save_related时,tastypie似乎没有检查任何授权

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

我正在使用tastypie v0.9.12-alpha

1 个答案:

答案 0 :(得分:2)

您可以修改save_related资源中的AJob方法,并将其定义为不修改AUser。你可以根据需要定义ForeignKey readonly,但是你必须提供dehydrate_user方法并在里面获取你想要返回的值。它将类似于return bundle['data'].user