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']
2、user_operation/views.pyurl
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
說明:繼承的類spa
(3)配置urlrest
router.register(r'userfavs', UserFavViewset, base_name="userfavs")
3、測試code
發送收藏請求router
查看收藏列表blog
重複收藏提示已經收藏繼承