• DRF实现购物车逻辑


    一、序列化

    from goods.models import Goods
    from .models import ShoppingCart
    from rest_framework import serializers
    from goods.serializers import GoodsSerializer
    
    
    class ShoppingCartDetaiSerializer(serializers.ModelSerializer):
        """
        购物车详情
        """
        goods = GoodsSerializer(read_only=True)
    
        class Meta:
            model = ShoppingCart
            fields = ['goods', 'nums']
    
    
    class ShoppingCartSerializer(serializers.Serializer):
        """
        购物车
        """
        user = serializers.HiddenField(default=serializers.CurrentUserDefault())
        nums = serializers.IntegerField(required=True, label='数量', min_value=1,
                                        error_messages={
                                            'min_value': '商品数量不能小于一',
                                            'required': '请选择购买数量'
                                        })
        goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all())
    
        def create(self, validated_data):
            user = self.context['request'].user
            nums = validated_data['nums']
            goods = validated_data['goods']
    
            # 获取购物车中的记录
            existed = ShoppingCart.objects.filter(user=user, goods=goods)
    
            # 如果没有则创建,有则加一
            if existed:
                existed = existed[0]
                existed.nums += nums
                existed.save()
            else:
                existed = ShoppingCart.objects.create(**validated_data)
    
            return existed
    
        def update(self, instance, validated_data):
            instance.nums = validated_data['nums']
            instance.save()
            return instance

    二、views.py

    from rest_framework import viewsets, mixins
    from rest_framework.permissions import IsAuthenticated
    from utils.permissions import IsOwnerOrReadOnly
    from rest_framework.authentication import SessionAuthentication
    from rest_framework_jwt.authentication import JSONWebTokenAuthentication
    from .serializers import ShoppingCartSerializer, ShoppingCartDetaiSerializer
    from .models import ShoppingCart
    
    
    class ShoppingCartViewSet(viewsets.ModelViewSet):
        """
        list:
           购物车列表
        read:
           购物车详情
        create:
           增加购物车
        update:
           更改购物车
        partial_update:
           部分更改
        delete:
           删除购物车
        """
        permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]
        authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication]
        lookup_field = 'goods_id'
    
        def get_queryset(self):
            return ShoppingCart.objects.filter(user=self.request.user)
    
        def get_serializer_class(self):
            if self.action == 'list':
                return ShoppingCartDetaiSerializer
            else:
                return ShoppingCartSerializer
  • 相关阅读:
    技术债务MartinFlower
    如何定义产品愿景
    领域驱动设计阶段知识总结
    领域驱动设计的价值
    什么是数字产品
    NestOS 发布:基于华为欧拉开源系统的云底座操作系统
    架子鼓MIDI及相关软件
    TM4 JDK1.8连接SqlServer报错:The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL)
    关于GPL协议的理解(开源与商用、免费与收费的理解)
    nest js 限制客户端在一定时间内的请求次数
  • 原文地址:https://www.cnblogs.com/mxsf/p/10687933.html
Copyright © 2020-2023  润新知