联合唯一可以使用django中的unique_together,和DRF中的UniqueTogetherValidator->https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator

unique_together

model

class UserFav(models.Model):
    """
    用户收藏
    """
    user = models.ForeignKey(User,verbose_name="用户",on_delete=False)
    goods = models.ForeignKey(Goods,verbose_name="商品",on_delete=False)
    add_time = models.DateTimeField(default=datetime.now,verbose_name="用户收藏")

    class Meta:
        verbose_name = "用户收藏"
        verbose_name_plural=verbose_name
        unique_together = (('user','goods'),)


    def __str__(self):
        return f'{self.goods.name}'

view

from django.shortcuts import render

from rest_framework import mixins,viewsets
from .serializers import UserFavSerializer
from .models import UserFav
# Create your views here.

class UserFavSetview(mixins.CreateModelMixin,mixins.ListModelMixin,
                     mixins.DestroyModelMixin,viewsets.GenericViewSet):

    serializer_class = UserFavSerializer
    queryset = UserFav.objects.all()

serializer

from rest_framework import serializers
from .models import UserFav
from rest_framework.validators import UniqueTogetherValidator


class UserFavSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = UserFav
        fields = ('id','user', 'goods')

UniqueTogetherValidator

基于unique_together只需改serializer

from rest_framework import serializers
from .models import UserFav
from rest_framework.validators import UniqueTogetherValidator


class UserFavSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = UserFav
        fields = ('id','user', 'goods')
        validators = [UniqueTogetherValidator(queryset=UserFav.objects.all(),fields=('user','goods'),message='您已收藏')]

 

posted on 2019-04-06 15:08  chester·chen  阅读(1588)  评论(0编辑  收藏  举报