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