1)序列化
user_operation/serializers.py
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from .models import UserFav class UserFvaSerializers(serializers.ModelSerializer): """ 用户收藏 """ user = serializers.HiddenField(default=serializers.CurrentUserDefault()) # validate实现唯一联合,一个商品只能收藏一次 validators = [ UniqueTogetherValidator(queryset=UserFav.objects.all(), fields=('user', 'goods'), message='已经收藏') ] class Meta: model = UserFav fields = ['user', 'goods', 'id']
二、user_operation/views.py
from rest_framework import viewsets, mixins from .serializers import UserFvaSerializers from .models import UserFav class UserFvaViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin): """ 用户收藏 """ queryset = UserFav.objects.all() serializer_class = UserFvaSerializers
说明:继承的类
- mixins.CreateModelMixin 添加收藏(相当于创建数据库)
- mixins.DestroyModelMixin 取消删除(相当于数据库删除)
- mixins.ListModelMixin 获取已收藏的商品列表
(3)配置url
router.register(r'userfavs', UserFavViewset, base_name="userfavs")
三、测试
发送收藏请求
查看收藏列表
重复收藏提示已经收藏