09-购物车、订单管理
一、购物车、订单管理
1、商品加入购物车的实现
根据前端分析,需要将加入购物车的逻辑以及序列化的需求分析好,然后再将需求满足。
trade/views.py:
from rest_framework import viewsets from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from utils.permissions import IsOwnerOrReadOnly from .serializers import ShoppingCartSerializers from .models import ShoppingCart class ShoppingCartViewset(viewsets.ModelViewSet): """ 购物车功能 list: 获取购物车详情 create: 加入购物车 delete: 删除购物车 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = ShoppingCartSerializers queryset = ShoppingCart.objects.all()
trade/serilizers.py:
from rest_framework import serializers from goods.models import Goods from .models import ShoppingCart class ShoppingCartSerializers(serializers.Serializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) nums = serializers.IntegerField(required=True,min_value=1,label="数量", error_messages={ "min_value":"商品数量不能小于一", "required":"请选择购买数量" }) goods = serializers.PrimaryKeyRelatedField(label="商品",queryset=Goods.objects.all(),required=True) 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
trade/models.py:
class ShoppingCart(models.Model): """ 购物车 """ user = models.ForeignKey(User, verbose_name=u"用户",on_delete=models.CASCADE) goods = models.ForeignKey(Goods, verbose_name=u"商品",on_delete=models.CASCADE) nums = models.IntegerField(default=0, verbose_name="购买数量") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = '购物车' verbose_name_plural = verbose_name unique_together = ("user", "goods") #创建联合唯一索引
MxShop/urls.py:
from rest_framework.routers import DefaultRouter from trade.views import ShoppingCartViewset router = DefaultRouter() #订单 购物车 router.register(r"shopcarts",ShoppingCartViewset,base_name="shopcarts")
测试加入购物车的接口,逻辑里面购物车必须大于一才能保存数据库,否则不能保存到数据库。经测试成功。
2、修改购物车的数量
class ShoppingCartViewset(viewsets.ModelViewSet): """ 购物车功能 list: 获取购物车详情 create: 加入购物车 delete: 删除购物车 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = ShoppingCartSerializers lookup_field = "goods_id"#传商品Id过来 def get_queryset(self): return ShoppingCart.objects.filter(user=self.request.user)
重写序列化器的update方法:
from rest_framework import serializers from goods.models import Goods from .models import ShoppingCart class ShoppingCartSerializers(serializers.Serializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) nums = serializers.IntegerField(required=True,min_value=1,label="数量", error_messages={ "min_value":"商品数量不能小于一", "required":"请选择购买数量" }) goods = serializers.PrimaryKeyRelatedField(label="商品",queryset=Goods.objects.all(),required=True) 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): """ 修改商品数量 :param instance: :param validated_data: :return: """ instance.nums = validated_data["nums"] instance.save() return instance
跑到浏览器中接口测试,delete方法不用重写,直接用。
然后现在后端服务器应该返回的是nums与goods的id,我们还需要返回goods的详情页面,因此我们需要重写序列化器。
from rest_framework import serializers from goods.models import Goods from .models import ShoppingCart from goods.serializers import GoodsSerializer class ShopCartDetailSerilizer(serializers.ModelSerializer): goods = GoodsSerializer(many=False,) class Meta: model = ShoppingCart fields = "__all__" class ShoppingCartSerializers(serializers.Serializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) nums = serializers.IntegerField(required=True,min_value=1,label="数量", error_messages={ "min_value":"商品数量不能小于一", "required":"请选择购买数量" }) goods = serializers.PrimaryKeyRelatedField(label="商品",queryset=Goods.objects.all(),required=True) 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): """ 修改商品数量 :param instance: :param validated_data: :return: """ instance.nums = validated_data["nums"] instance.save() return instance
from rest_framework import viewsets from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from utils.permissions import IsOwnerOrReadOnly from .serializers import ShoppingCartSerializers,ShopCartDetailSerilizer from .models import ShoppingCart # Create your views here. class ShoppingCartViewset(viewsets.ModelViewSet): """ 购物车功能 list: 获取购物车详情 create: 加入购物车 delete: 删除购物车 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = ShoppingCartSerializers lookup_field = "goods_id"#传商品Id过来 def get_serializer_class(self): if self.action == "list": return ShopCartDetailSerilizer else: return ShoppingCartSerializers def get_queryset(self): return ShoppingCart.objects.filter(user=self.request.user)
运行成功,现在前端与后端联调:
购物车与配送地址都成功啦。
3、订单管理接口
class OrderViewset(mixins.ListModelMixin,mixins.RetrieveModelMixin,mixins.CreateModelMixin, mixins.DestroyModelMixin,viewsets.GenericViewSet): """ list: 获取订单 delete: 删除订单 create: 新增订单 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = OrderSerializer def get_queryset(self): return OrderInfo.objects.filter(user=self.request.user) def get_serializer_class(self): if self.action == "retrieve": return OrderDetailSerializer return OrderSerializer def perform_create(self, serializer): order = serializer.save() shop_carts = ShoppingCart.objects.filter(user=self.request.user) for shop_cart in shop_carts: order_goods = OrderGoods() order_goods.goods = shop_cart.goods order_goods.goods_num = shop_cart.nums order_goods.order = order order_goods.save() shop_cart.delete() return order
class OrderGoodsSerializer(serializers.ModelSerializer): goods = GoodsSerializer(many=False) class Meta: model = OrderGoods fields = "__all__" class OrderDetailSerializer(serializers.ModelSerializer): #OrderInfo中的外键order需要设置relate_name goods = OrderGoodsSerializer(many=True) class Meta: model = OrderInfo fields = "__all__" class OrderSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) pay_status = serializers.CharField(read_only=True) order_sn = serializers.CharField(read_only=True) trade_no = serializers.CharField(read_only=True) pay_time = serializers.CharField(read_only=True) def generate_order_sn(self): #当前时间+userID+随机数 from random import Random random_int = Random() order_sn = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"), userid=self.context["request"].user.id,ranstr=random_int.randint(10,99)) return order_sn def validate(self, attrs): attrs["order_sn"] = self.generate_order_sn() return attrs class Meta: model = OrderInfo fields = "__all__"
订单接口涉及到增删查,因此继承mixins的相关类,在进行相关的序列化操作。以及相关记录的隐藏设置权限,例如用户的隐藏,