Django: Object of type QuerySet is not JSON serializable

Question:

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})

Asked By: Destiny Franks

||

Answers:

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})
Answered By: ruddra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.