Django Tastype:对许多字段的权限

2024-10-03 09:07:58 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以仅对我的模型的m2m字段授予删除权限? 让我们想想:

class Site(models.Model):
    name = models.CharField(max_length=50)
    favourited_by = models.ManyToManyField(User)

如果我编写此模型资源:

class SiteResource(ModelResource):
    class Meta:
        queryset = Site.objects.all()
        resource_name = 'Site'
        allowed_methods = ['post', 'get', 'delete']

我为整个模型授予了删除权限,但我只希望能够从“favorited\ u by”字段中删除条目。有什么办法可以做到吗


Tags: name模型权限bymodelmodelssitelength
1条回答
网友
1楼 · 发布于 2024-10-03 09:07:58

根据定义,在该端点上执行删除操作应删除整个对象

但是,如果您正在寻找一个自定义行为,那么您可以用如下内容覆盖obj_delete

def obj_delete(self, bundle, **kwargs):
    # Get the object and raise NotFound if couldn't find
    try:
        bundle.obj = self.obj_get(bundle=bundle, **kwargs)
    except ObjectDoesNotExist:
        raise NotFound("A model instance matching the provided arguments could not be found.")

    #Here you should do any kind of validation before deleting

    # And then remove using the parameter you passed (for example user_id)
    bundle.obj.favourited_by.remove(User.objects.get(id=bundle.data['user_id']))  #pass in the user_id
    return

相关问题 更多 >