简体   繁体   English

“ Mycart”类型的对象在Django中无法JSON序列化

[英]Object of type 'Mycart' is not JSON serializable in Django

I want to add dictionary(having models) datatype object to request.session but getting "Object of type 'Mycart' is not JSON serializable in Django" 我想向request.session添加字典(具有模型)数据类型对象,但获取“类型'Mycart'的对象在Django中无法JSON序列化”

product_details = {}
for product in products_in_cart:
    product_details.update({product.id: 
    (product,request.POST['quantity'+str(product.product.id)])})  
request.session['product_details'] = product_details

I expect the dictionary updated in session but the actual output is "Object of type 'Mycart' is not JSON serializable in Django" 我希望字典在会话中更新,但实际输出为“ Mycart类型的对象在Django中不是JSON可序列化的”

The problem is with the product which is the first parameter of your tuple inside of your dictionary. 问题在于product ,它是字典中元组的第一个参数。 you need to serialize it before you can use it in your tuple like this: 您需要先对其进行序列化,然后才能在元组中使用它,如下所示:

 from django.core import serializers

 product_details = {}
 for product in products_in_cart:
     s_product = serializers.serialize("json", [product])
     product_details.update({product.id: 
    (s_product,request.POST['quantity'+str(product.id)])})  
     request.session['product_details'] = product_details

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM