Django REST framework+Vue to build a fresh supermarket (9) 10. Shopping cart, order management and payment functions

Django REST framework+Vue to build a fresh supermarket (9) 10. Shopping cart, order management and payment functions

10. Shopping cart, order management and payment functions

10.1. Add products to the shopping cart

(1) trade/serializer.py

# trade/serializer.py
__author__ ='derek'

from .models import ShoppingCart
from rest_framework import serializers
from goods.models import Goods

class ShopCartSerializer(serializers.Serializer):
    #Get the currently logged-in user
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    nums = serializers.IntegerField(required=True, label="quantity",min_value=1,
                                    error_messages={
                                        "min_value":"The quantity of goods cannot be less than one",
                                        "required": "Please select the purchase quantity"
                                    })
    #Here is the inheritance of Serializer, you must specify the queryset object, if you inherit ModelSerializer, you do not need to specify
    #goods is a foreign key, you can get all the values ​​in the goods object by this method
    goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all())

    #Inherited Serializer has no save function, you must write a create method
    def create(self, validated_data):
        # validated_data is the processed data
        #Get current user
        # view: self.request.user; serizlizer: self.context["request"].user
        user = self.context["request"].user
        nums = validated_data["nums"]
        goods = validated_data["goods"]

        existed = ShoppingCart.objects.filter(user=user, goods=goods)
        #If there is a record in the shopping cart, the quantity is +1
        #If the shopping cart has no record, create it
        if existed:
            existed = existed[0]
            existed.nums += nums
            existed.save()
        else:
            #Add to Cart
            existed = ShoppingCart.objects.create(**validated_data)

        return existed

(2) trade/views.py

# trade/views.py

from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from .serializers import ShopCartSerializer
from .models import ShoppingCart

class ShoppingCartViewset(viewsets.ModelViewSet):
    """
    Shopping cart function
    list:
        Get shopping cart details
    create:
        add to Shopping Cart
    delete:
        Delete shopping record
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    serializer_class = ShopCartSerializer

    def get_queryset(self):
        return ShoppingCart.objects.filter(user=self.request.user

(3) Configure url

# Configure the url of the shopping cart
router.register(r'shopcarts', ShoppingCartViewset, base_name="shopcarts")

10.1. Add the number of shopping carts

Serializer inherits BaseSerializer, but there is no update method in Seriazer, all add an update method

trade/serializer.py

 def update(self, instance, validated_data):
        # Modify the quantity of goods
        instance.nums = validated_data["nums"]
        instance.save()
        return instance

Pass the product id in the view

 lookup_field = "goods_id"

10.3. Joint debugging of vue and shopping cart interface

You can see the product details in the shopping cart, you need to write a serializer for the product details, and you need to dynamically set the serializer in the view

(1) trade/serializer.py

class ShopCartDetailSerializer(serializers.ModelSerializer):
    '''
    Shopping cart product detail information
    '''
    # One shopping cart corresponds to one product
    goods = GoodsSerializer(many=False, read_only=True)
    class Meta:
        model = ShoppingCart
        fields = ("goods", "nums")

(2) trade/views.py

Need to dynamically select serializer

    def get_serializer_class(self):
        if self.action =='list':
            return ShopCartDetailSerializer
        else:
            return ShopCartSerializer

10.4. Order management interface

(1) trade/serializer.py

The user adds goods to the shopping cart, clicks to go to the shopping cart for settlement, fills in the address and leaves a message, settles to generate an order, in the member center My Order, you can see the order list, and click the order to see the detailed information of the order.

#Items in the order
class OrderGoodsSerialzier(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)
    class Meta:
        model = OrderGoods
        fields = "__all__"

#Order product information
# The goods field needs to nest an OrderGoodsSerializer
class OrderDetailSerializer(serializers.ModelSerializer):
    goods = OrderGoodsSerialzier(many=True)
    class Meta:
        model = OrderInfo
        fields = "__all__"

class OrderSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    #When generating the order, these do not need to post
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    pay_type = serializers.CharField(read_only=True)


    def generate_order_sn(self):
        #Generate order number
        # Current time + userid + random number
        from random import Random
        random_ins = 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_ins.randint(10, 99))
        return order_sn

    def validate(self, attrs):
        #validate add order_sn, and then you can save in the view
        attrs["order_sn"] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = "__all__"

(2) trade/views.py

class OrderViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin,
                   viewsets.GenericViewSet):
    """
    Order management
    list:
        Get personal order
    delete:
        Delete order
    create:
        New order
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = OrderSerializer
    #Dynamic configuration serializer
    def get_serializer_class(self):
        if self.action == "retrieve":
            return OrderDetailSerializer
        return OrderSerializer
    #Get order list
    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user)
    
    #There are two more steps before the order is submitted and saved, so here is the custom perform_create method
    #1. Save the goods in the shopping cart to OrderGoods
    #2. Empty the shopping cart
    def perform_create(self, serializer):
        order = serializer.save()
        # Get all items in the shopping cart
        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()
            #Empty shopping cart
            shop_cart.delete()
        return order

(3) Configure url

# Configure the url of the order
router.register(r'orders', OrderViewset, base_name="orders")
Reference: https://cloud.tencent.com/developer/article/1103640 Django REST framework+Vue to create a fresh supermarket (9) 10. Shopping cart, order management and payment functions-Cloud + Community-Tencent Cloud