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/

# trade/
__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(
    nums = serializers.IntegerField(required=True, label="quantity",min_value=1,
                                        "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
            #Add to Cart
            existed = ShoppingCart.objects.create(**validated_data)

        return existed

(2) trade/

# trade/

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
        Get shopping cart details
        add to Shopping Cart
        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


 def update(self, instance, validated_data):
        # Modify the quantity of goods
        instance.nums = validated_data["nums"]
        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/

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/

Need to dynamically select serializer

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

10.4. Order management interface

(1) trade/

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(
    #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"),
                                                       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/

class OrderViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin,
    Order management
        Get personal order
        Delete order
        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 =
        # 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
            #Empty shopping cart
        return order

(3) Configure url

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