仅当请求作者与实例作者相同时,我才想更新模型的实例。
我猜可以在更新方法中做到这一点
def update(self, request, *args, **kwargs):
if request.user == self.get_object().user
do_things()
我该怎么办?是否必须在每个ModelViewSet或ListAPIView上编写更新?还是有一种方法可以编写自定义权限来实现此目的。
答案 0 :(得分:3)
您可以实现custom permission。以下示例来自docs,并进行了修改以适合您的用例:
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `user` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Instance must have an attribute named `user`.
return obj.user == request.user