DRF用戶收藏接口實現

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

  •  mixins.CreateModelMixin         添加收藏(至關於建立數據庫)
  •  mixins.DestroyModelMixin       取消刪除(至關於數據庫刪除)
  •  mixins.ListModelMixin             獲取已收藏的商品列表

 (3)配置urlrest

router.register(r'userfavs', UserFavViewset, base_name="userfavs")

3、測試code

發送收藏請求router

查看收藏列表blog

重複收藏提示已經收藏繼承

相關文章
相關標籤/搜索