订单同样 可以修改 创建 删除 查看这些功能
views
class OrderViewset(viewsets.GenericViewSet, mixins.ListModelMixin,
mixins.CreateModelMixin, mixins.RetrieveModelMixin,
mixins.DestroyModelMixin):
"""
订单管理
list:
获取个人订单
create:
创建订单
delete:
删除订单
"""
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
# serializer_class = OrderSerializer
def get_serializer_class(self): #动态获取serializer
if self.action == 'retrieve':
return OrderDetailSerializer
return OrderSerializer
def get_queryset(self):
# 获取属于用户的购物车list
return OrderInfo.objects.filter(user=self.request.user)
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
serializer
class OrderGoodsSerializer(serializers.ModelSerializer): #商品详情
goods = GoodsSerializer(many=False) #一对一的商品
class Meta:
model= OrderGoods
fields = '__all__'
class OrderDetailSerializer(serializers.ModelSerializer):#订单详情 #订单list用
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) #这些设置为read_only 不用设置 由后端生成
order_sn = serializers.CharField(read_only=True)
trade_no = serializers.CharField(read_only=True)
pay_time = serializers.DateTimeField(read_only=True)
add_time = serializers.DateTimeField(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): #添加订单号
attrs['order_sn'] = self.generate_order_sn()
return attrs
class Meta:
model = OrderInfo
fields = "__all__"
网友评论