<Django object > is not JSON serializable
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_dictdata = 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.
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 JsonResponsequeryset = YourModel.objects.filter(some__filter="some value").values()return JsonResponse({"models_to_return": list(queryset)})
I found that this can be done rather simple using the ".values" method, which also gives named fields:
result_list = list(my_queryset.values('first_named_field', 'second_named_field'))return HttpResponse(json.dumps(result_list))
"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values