在项目的工具包新建permissions.py文件
权限认证:
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
对象级权限仅允许对象的所有者对其进行编辑
假设模型实例具有`user`属性。
"""
def has_object_permission(self, request, view, obj):
# 任何请求都允许读取权限,
# 所以我们总是允许GET,HEAD或OPTIONS 请求.
if request.method in permissions.SAFE_METHODS:
return True
# 示例必须要有一个名为`user`的属性3
return obj.user == request.user
serializer:
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from apps.user_operation.models import UserFav
#查询收藏
class UserFavDetailSerializer(serializers.ModelSerializer):
goods=GoodsSerializer()
class Meta:
model=UserFav
fields=("user","id")
class UserFavSerializer(serializers.ModelSerializer):
#获取当前登陆的用户
user=serializers.HiddenField(
default=serializers.CurrentUserDefault()
)
class Meta:
model=UserFav
validators = [
UniqueTogetherValidator(
queryset=UserFav.objects.all(),
fields=('user', 'goods'),
message="已经收藏"
)
]
fields=("user","goods","id")
view:
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from apps.user_operation.models import UserFav
from .serializer import UserFavSerializer
from .serializer import UserFavDetailSerializer
from utils.permissions import IsOwnerOrReadOnly
# Create your views here.
class UserFavViewSet(mixins.CreateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
"""
用户收藏功能
list: 用户收藏列表
create:创建用户收藏
destroy:删除用户收藏
retrieve:用户是否收藏该商品
"""
# serializer_class = UserFavSerializer
# 添加和查询收藏的serializer都不一样所以需要动态设置
def get_serializer_class(self):
if self.action == "list":
return UserFavDetailSerializer
if self.action == "create":
return UserFavSerializer
return UserFavDetailSerializer
#IsAuthenticated:判断用户是否登陆,IsOwnerOrReadOnly:判断用户是否是操作当前用户的收藏
permission_classes = (IsAuthenticated,IsOwnerOrReadOnly )
# jwt认证,SessionAuthentication:在urls中能进行登陆
authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
lookup_field = "goods_id"
# 重写queryset方法,因为只需要获取当前用户的收藏表
def get_queryset(self):
return UserFav.objects.filter(user=self.request.user)