from rest_framework.permissions import BasePermission,SAFE_METHODS
classIsOwnerOrReadOnly(BasePermission):"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""defhas_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 SAFE_METHODS:
returnTrue# Instance must have an attribute named `owner`.return obj.user == request.user
登录才能访问的权限
from rest_framework.permissions import IsAuthenticated
class ModelViewSet(mixins.RetrieveModelMixin,mixins.ListModelMixin,mixins.DestroyModelMixin,viewsets.GenericViewSet):
...
permission_classes =(IsAuthenticated,IsOwnerOrReadOnly)
#设置RetrieveModelMixin查找的字段,id为url路径最后的参数
lookup_field = "field_id"...