close

[Solved] Django object is not JSON serializable

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Django object is not JSON serializable in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Django object is not JSON serializable Error Occurs?

Today I get the following error Django object is not JSON serializable in python.

How To Solve Django object is not JSON serializable Error ?

  1. How To Solve Django object is not JSON serializable Error ?

    To Solve Django object is not JSON serializable Error In your case, self.get_queryset() contains a mix of django objects and dicts inside.

  2. Django object is not JSON serializable

    To Solve Django object is not JSON serializable Error In your case, self.get_queryset() contains a mix of django objects and dicts inside.

Solution 1

simplejson and json don’t work with django objects well.

Django’s built-in serializers can only serialize querysets filled with django objects:

data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")

In your case, self.get_queryset() contains a mix of django objects and dicts inside.

One option is to get rid of model instances in the self.get_queryset() and replace them with dicts using model_to_dict:

from django.forms.models import model_to_dict

data = self.get_queryset()

for item in data:
   item['product'] = model_to_dict(item['product'])

return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")

Hope that helps.

Solution 2

The easiest way is to use a JsonResponse.

For a queryset, you should pass a list of the the values for that queryset, like so:

from django.http import JsonResponse

queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read