1、序列化ui
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
2、views.pyspa
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