码迷,mamicode.com
首页 > 其他好文 > 详细

09-购物车、订单管理

时间:2019-11-27 17:34:39      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:elm   required   reg   测试   and   error   cad   read_only   color   

一、购物车、订单管理

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)
trade/views.py

重写序列化器的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
trade/serializers.py

跑到浏览器中接口测试,delete方法不用重写,直接用。

技术图片

 

 技术图片

 

 然后现在后端服务器应该返回的是numsgoodsid,我们还需要返回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
trade/serializers.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,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)
trade/views.py

技术图片

 

 运行成功,现在前端与后端联调:

技术图片

 

 购物车与配送地址都成功啦。

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
trade/views.py
技术图片
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__"
trade/serializers.py

订单接口涉及到增删查,因此继承mixins的相关类,在进行相关的序列化操作。以及相关记录的隐藏设置权限,例如用户的隐藏,

09-购物车、订单管理

标签:elm   required   reg   测试   and   error   cad   read_only   color   

原文地址:https://www.cnblogs.com/lishuntao/p/11918372.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!