Django REST framework+Vue 打造生鮮超市(九)

小說:哪里有批發精品繡球花種子?作者:安丁王戲更新時間:2019-05-27字數:97862

Django REST framework+Vue 打造生鮮超市(九)


十、購物車、訂單管理和支付功能

?10.1.添加商品到購物車

(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):
    #獲取當前登錄的用戶
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    nums = serializers.IntegerField(required=True, label="數量",min_value=1,
                                    error_messages={
                                        "min_value":"商品數量不能小于一",
                                        "required": "請選擇購買數量"
                                    })
    #這里是繼承Serializer,必須指定queryset對象,如果繼承ModelSerializer則不需要指定
    #goods是一個外鍵,可以通過這方法獲取goods object中所有的值
    goods = serializers.PrimaryKeyRelatedField(required=True, queryset=Goods.objects.all())

    #繼承的Serializer沒有save功能,必須寫一個create方法
    def create(self, validated_data):
        # validated_data是已經處理過的數據
        #獲取當前用戶
        # 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)
        #如果購物車中有記錄,數量+1
        #如果購物車車沒有記錄,就創建
        if existed:
            existed = existed[0]
            existed.nums += nums
            existed.save()
        else:
            #添加到購物車
            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):
    """
    購物車功能
    list:
        獲取購物車詳情
    create:
        加入購物車
    delete:
        刪除購物記錄
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    serializer_class = ShopCartSerializer

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

(3)配置url

# 配置購物車的url
router.register(r"shopcarts", ShoppingCartViewset, base_name="shopcarts")

?

?10.1.添加購物車數量

Serializer繼承BaseSerializer,但是Seriazer中并沒有重新update方法,所有添加一個update方法

trade/serializer.py

 def update(self, instance, validated_data):
        # 修改商品數量
        instance.nums = validated_data["nums"]
        instance.save()
        return instance

在view中要把商品id傳過去

 lookup_field = "goods_id"

10.3.vue和購物車接口聯調

購物車中可以看商品詳情,需要寫一個商品詳情的serializer,所有在view中需要動態設置serializer

(1)trade/serializer.py

class ShopCartDetailSerializer(serializers.ModelSerializer):
    """
    購物車商品詳情信息
    """
    # 一個購物車對應一個商品
    goods = GoodsSerializer(many=False, read_only=True)
    class Meta:
        model = ShoppingCart
        fields = ("goods", "nums")

(2)trade/views.py

需要動態選擇serializer

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

?

10.4.訂單管理接口

(1)trade/serializer.py

用戶添加商品到購物車,點去購物車結算,填上地址留言,結算生成訂單,在會員中心我的訂單里面,可以看到訂單列表,點訂單可以看到訂單的詳細信息。

#訂單中的商品
class OrderGoodsSerialzier(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)
    class Meta:
        model = OrderGoods
        fields = "__all__"

#訂單商品信息
# goods字段需要嵌套一個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()
    )
    #生成訂單的時候這些不用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):
        #生成訂單號
        # 當前時間+userid+隨機數
        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中添加order_sn,然后在view中就可以save
        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):
    """
    訂單管理
    list:
        獲取個人訂單
    delete:
        刪除訂單
    create:
        新增訂單
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = OrderSerializer
    #動態配置serializer
    def get_serializer_class(self):
        if self.action == "retrieve":
            return OrderDetailSerializer
        return OrderSerializer
    #獲取訂單列表
    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user)
    
    #在訂單提交保存之前還需要多兩步步驟,所以這里自定義perform_create方法
    #1.將購物車中的商品保存到OrderGoods中
    #2.清空購物車
    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

(3)配置url

# 配置訂單的url
router.register(r"orders", OrderViewset, base_name="orders")

?

當前文章:http://www.hfcxdn.com/home/lc02ypj4qu.html

發布時間:2019-05-27 17:10:20

北京適合種棣棠花嗎? 哪里有賣劍麻小苗的? 平枝荀子批發去哪里? 紫藤苗木的種植規格是多少? 東北哪里有批發月季苗? 爬山虎價格哪家準確? 他家的紅楓樹為什么天天有那么多人去買,想知道原因嗎? 玫瑰樹苗哪里有,來到江蘇長景走一走! 高羊茅和狗牙草哪個好? 不怕除草劑的牧草有哪些?

紫荊花樹在廣西能種嗎? 內蒙古扶芳藤都在哪里買的? 70cm高小葉黃楊什么價格? 紫藤花籽怎么種呢? 紫云英種多久才開花?  遼寧適合種植結縷草嗎? 鳳仙花發芽溫度是多少度? 南非萬壽菊包衣種子是什么? 十一月還能種植向日葵嗎? 胡枝子花期是什么時候? 三角楓種子批發去哪里?

編輯:杜華

我要說兩句: (0人參與)

發布
捕鱼达人之深海狩猎