简体   繁体   中英

Django JsonResponse not returning serialized data

Why JsonResponce not able to serialized the data, i think I'm getting this error because of for x in cart_obj.products.all() Error:

raise TypeError(f'Object of type {o.__class__.__name__} 
TypeError: Object of type method is not JSON serializable



def cart_json_view(request):    # defined for ajax
    cart_obj, new_obj = Cart.objects.create_cart_or_get_cart(request)
    products = [{
        "id": x.id,
        "url": x.get_absolute_url(),
        "name": x.name,
        "price": x.price
    } for x in cart_obj.products.all()]
    cart_data = {"products": products, "subtotal": cart_obj.subtotal, "total": cart_obj.total}
    return JsonResponse(cart_data)

need to convert cart_dat(python dictionary) to text add this line

from django.core.serializers import serialize
from django.core.serializers.json import DjangoJSONEncoder
.
.
.
return JsonResponse(json.loads(serialize('json', cart_data)), safe=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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