Home > Back-end >  Django: Object of type QuerySet is not JSON serializable
Django: Object of type QuerySet is not JSON serializable

Time:11-08

I am trying to remove items from cart using Jquery and Django, i have written the logic to do this but i keep getting this errror that says Object of type QuerySet is not JSON serializable, i can seem to know what the problem is because i have tried converting the code below to list using list() method in django and also values() but it still does not work as expected.

views.py

def RemoveWishlist(request):
    wishlist = Wishlist.objects.filter(user=request.user)
    ...
    context = {
        "bool":True,
        "wishlist":wishlist
    }
    t = render_to_string('core/async/wishlist-list.html', context)
    return JsonResponse({'data':t,'wishlist':wishlist})

CodePudding user response:

As the error mentions, queryset is not JSON serializable. Hence you can make it into JSON using Django's serializers and pass it to JsonResponse class initiation:

from django.core import serializers
....
qs_json = serializers.serialize('json', wishlist)
return JsonResponse({'data':t,'wishlist':qs_json})
  • Related