请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

订单存储商品问题

老师, 课程里面创建订单的时候是将购物车所有的商品全部加入订单中, 但是现在淘宝上市根据选取的商品来创建订单, 在serializer中该使用啥字段保存商品和商品数量呀,

class OrderInfoSerializer(serializers.Serializer):
    goods = serializers.IntegerField(required=True, label="商品", error_messages={
        "required": "商品不能为空"
    })
    goods_num = serializers.IntegerField(required=True, label="商品数量", min_value=1, error_messages={
        "required": "商品数量不能为空",
        "min_value": "商品数量不能小于1"
    })


class GoodsOrderSerializer(serializers.Serializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    order_no = serializers.CharField(read_only=True)
    status = serializers.IntegerField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_message = serializers.CharField(label="订单留言", required=False)
    order_amount = serializers.DecimalField(max_digits=20, decimal_places=2, required=True,
                                            error_messages={
                                                "required": "订单金额不能为空"
                                            })
    address = serializers.CharField(required=True, error_messages={
        "required": "请填写收货地址"
    })
    signer_name = serializers.CharField(label="收件人", required=False)
    signer_mobile = serializers.CharField(required=True, max_length=11, error_messages={
        "required": "请填写收件人手机号码",
        "max_length": "手机号码有误",
    })
    goods = OrderInfoSerializer(many=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 create(self, validated_data):
        order_no = self.generate_order_sn()
        validated_data["order_no"] = order_no
        goods = validated_data["goods"]
        del validated_data["goods"]
        goods_order = GoodsOrder.objects.create(**validated_data)

        for good in goods:
            order_info = OrderInfo()
            goods = Goods.objects.filter(id=good["goods"]).first()
            order_info.goods = goods
            order_info.goods_num = good["goods_num"]
            order_info.order_id = goods_order.id
            order_info.save()

        return goods_order

报错:

Internal Server Error: /trade/order/
Traceback (most recent call last):
  File "D:\vienv\env_django\lib\site-packages\rest_framework\fields.py", line 454, in get_attribute
    return get_attribute(instance, self.source_attrs)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\fields.py", line 94, in get_attribute
    instance = getattr(instance, attr)
AttributeError: 'GoodsOrder' object has no attribute 'goods'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\vienv\env_django\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "D:\vienv\env_django\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\vienv\env_django\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\vienv\env_django\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\viewsets.py", line 114, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "D:\vienv\env_django\lib\site-packages\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\mixins.py", line 20, in create
    headers = self.get_success_headers(serializer.data)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\serializers.py", line 562, in data
    ret = super().data
  File "D:\vienv\env_django\lib\site-packages\rest_framework\serializers.py", line 260, in data
    self._data = self.to_representation(self.instance)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
    attribute = field.get_attribute(instance)
  File "D:\vienv\env_django\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
    raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `goods` on serializer `GoodsOrderSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `GoodsOrder` instance.
Original exception text was: 'GoodsOrder' object has no attribute 'goods'.

正在回答 回答被采纳积分+3

1回答

bobby 2020-09-20 09:40:16

如果你要选择商品的话 那么你有两种方案: 1. 前端配合选择商品以及数量传递给后端,然后批量提交这些信息到后端,然后后端来批量保存 2. 给购物车中的条目增加一个字段 selected表示是否选中,前端点击选择以后给后端提交一个请求将当前条目改为已经选中,然后当提交订单的时候后端从购物车中挑出已经selected的条目写入到订单表中就行了

你这里的报错是GoodsOrder这张表中没有定义goods这个列?

0 回复 有任何疑惑可以回复我~
  • 提问者 慕妹7002893 #1
    如果是第一种情况的话, 是不是需要新开一个保存订单商品的接口, 还是就在创建订单的时候一起传过来?
    回复 有任何疑惑可以回复我~ 2020-09-21 10:21:20
  • bobby 回复 提问者 慕妹7002893 #2
    不用,你上传订单新的时候将商品的id和数量一起传递过去啊
    回复 有任何疑惑可以回复我~ 2020-09-22 10:16:51
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信