1、自定義權限數據庫
utils文件夾下新建permissions.py,代碼以下:spa
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 `owner` 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 `owner`. #obj至關於數據庫中的model,這裏要把owner改成咱們數據庫中的user return obj.user == request.user
這個官網有實例,直接複製過來就能夠了,把其中的owner改成user便可rest
2、user_operation/viewscode
from rest_framework import viewsets from rest_framework import mixins from .models import UserFav from .serializers import UserFavSerializer from rest_framework.permissions import IsAuthenticated from utils.permissions import IsOwnerOrReadOnly from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.authentication import SessionAuthentication class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin): ''' 用戶收藏 ''' serializer_class = UserFavSerializer #permission是用來作權限判斷的 # IsAuthenticated:必須登陸用戶;IsOwnerOrReadOnly:必須是當前登陸的用戶 permission_classes = (IsAuthenticated,IsOwnerOrReadOnly) #auth使用來作用戶認證的 authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication) #搜索的字段 lookup_field = 'goods_id' def get_queryset(self): #只能查看當前登陸用戶的收藏,不會獲取全部用戶的收藏 return UserFav.objects.filter(user=self.request.user)
說明:jwt