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

 

posted @ 2019-04-11 10:12  梦醒时分c  阅读(446)  评论(0编辑  收藏  举报