Django-Product类型的对象不是JSON可序列化的[重复]

dtcbnfnu  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(134)

此问题已在此处有答案

is not JSON serializable(8个回答)
3天前关闭。
环境:
申请方式:POST请求URL:http://127.0.0.1:8000/orders/create/

Traceback (most recent call last):
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 138, in __call__
    response = self.process_response(request, response)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\middleware.py", line 59, in process_response
    request.session.save()
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\backends\db.py", line 82, in save
    obj = self.create_model_instance(data)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\backends\db.py", line 69, in create_model_instance
    session_data=self.encode(data),
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\sessions\backends\base.py", line 94, in encode
    return signing.dumps(
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\signing.py", line 150, in dumps
    return TimestampSigner(key, salt=salt).sign_object(
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\signing.py", line 228, in sign_object
    data = serializer().dumps(obj)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\signing.py", line 125, in dumps
    return json.dumps(obj, separators=(",", ":")).encode("latin-1")
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\shafquet Naghmi\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '

Exception Type: TypeError at /orders/create/
Exception Value: Object of type Product is not JSON serializable

我正在尝试使用

product=json.dumps(item['product'],cls=DjangoJSONEncoder)

但是我还是得到了同样的错误。有很多这样的问题,但我不能连接点。谢谢

def create_order(request):
    cart=Cart(request)
    if request.method=='POST':
        form=OrderCreateForm(request.POST)
        if form.is_valid():
            order=form.save()
            for item in cart:
                #product=json.dumps(item['product'],cls=DjangoJSONEncoder)
                #product = serializers.serialize("json", [item['product']])
                OrderItem.objects.create(order=order,product=(item['product']),price=(item['price']),quantity=item['quantity'])
            cart.clear()
            #order_created(order.id)
        #return render(request,'orders/created.html',{'order':order})
        request.session['order_id']=order.id
        return redirect(reverse('payment:process'))
    else:
        form=OrderCreateForm()
    context={'form':form,'cart':cart}
    return render(request,'orders/create_order.html',context)

cart.py

def __iter__(self):
        product_ids=self.cart.keys()
        products=Product.objects.filter(id__in=product_ids)
        for product in products:
            self.cart[str(product.id)]['product']=(product)
        for item in self.cart.values():
            item['price']=float((item['price']))
            item['total_price']=item['price']*item['quantity']
            yield item
mhd8tkvw

mhd8tkvw1#

我认为您可以使用以下选项之一:

from django.forms.models import model_to_dict
product=json.dumps(model_to_dict(item['product']))

或者

product = serializers.serialize("json", [item['product'], ])

有关serializer的更多信息,请参阅文档。

相关问题