1.序列化器
from rest_framework import serializers
from cart.models import Cart
from goods.models import GoodsGroup, Goods, Detail, GoodsBanner, Collect
from goods.serializers import GoodsSerializers
class CartSerializers(serializers.ModelSerializer):
"""商品分类序列化器"""
class Meta:
model = Cart
fields = "__all__"
class ReadCartSerializers(serializers.ModelSerializer):
"""商品分类序列化器"""
goods = GoodsSerializers()
class Meta:
model = Cart
fields = "__all__"
2.视图类
from rest_framework import mixins, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from cart.models import Cart
from cart.serializers import CartSerializers, ReadCartSerializers
class CartView(GenericViewSet, mixins.CreateModelMixin, mixins.ListModelMixin):
serializer_class = CartSerializers
queryset = Cart.objects.all()
# 设置认证用户才能有访问权限
permission_classes = [IsAuthenticated]
# 重写获取序列化器的方法,用于区分是读数据还是写数据
def get_serializer_class(self):
""" 实现读写操作不用的序列化器 """
if self.action == 'list':
return ReadCartSerializers
else:
return self.serializer_class
def create(self, request, *args, **kwargs):
# 获取用户信息
user = request.user
# 获取参数
goods = request.data.get('goods')
# 1. 校验用户的购物车是否有此商品
if Cart.objects.filter(user=user, goods=goods).exists():
# 这个用户已经添加过该商品到购物车,直接修改商品数量
cart_obj = Cart.objects.get(user=user, goods=goods)
cart_obj.number += 1
cart_obj.save()
# 对这个商品进行序列化
serializer = self.get_serializer(cart_obj)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
request.data['user'] = user.id
return super().create(request, *args, **kwargs)
def list(self, request, *args, **kwargs):
queryset = self.get_queryset().filter(user=request.user)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)