• django drf unique_together和UniqueTogetherValidator


    联合唯一可以使用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='您已收藏')]
  • 相关阅读:
    C++ Builder XE2随意学习 (5) > 我的学习路线
    麻省理工公开课:电路和电子学 (2) > 基本电路分析法
    C++ Builder XE2随意学习 (4) > Delphi XE2官方视频教程31天
    日志收集系统elk
    mysql笔记第一天: 介绍和MySQL编译安装
    rsync服务搭建2018.5.8 [优化后最终版]
    docker基础使用和资源限制
    zabbix第一天 zabbix安装,添加监控项
    你好,测试markdown
    LVM扩容案例
  • 原文地址:https://www.cnblogs.com/chenyishi/p/10661826.html
Copyright © 2020-2023  润新知