I have the following code for serializing the queryset;
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.simplejson.dumps(list(self.get_queryset())),
mimetype="application/json")
And following is my get_querset()
[{'product': <Product: hederello ()>, u'_id': u'9802', u'_source': {u'code': u'23981', u'facilities': [{u'facility': {u'name': {u'fr': u'G\xe9n\xe9ral', u'en': u'General'}, u'value': {u'fr': [u'bar', u'r\xe9ception ouverte 24h/24', u'chambres non-fumeurs', u'chambres familiales',.........]}]
Which I need to serialize. But it says not able to serialize the <Product: hederello ()>
. Because list composed of both django objects and dicts. Any ideas ?
This question is related to
python
django
json
serialization
django-class-based-views
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
Another great way of solving it while using a model is by using the values()
function.
def returnResponse(date):
response = ScheduledDate.objects.filter(date__startswith=date).values()
return Response(response)
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
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)})
Our js-programmer asked me to return the exact JSON format data instead of a json-encoded string to her.
Below is the solution.(This will return an object that can be used/viewed straightly in the browser)
import json
from xxx.models import alert
from django.core import serializers
def test(request):
alert_list = alert.objects.all()
tmpJson = serializers.serialize("json",alert_list)
tmpObj = json.loads(tmpJson)
return HttpResponse(json.dumps(tmpObj))
First I added a to_dict method to my model ;
def to_dict(self):
return {"name": self.woo, "title": self.foo}
Then I have this;
class DjangoJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, models.Model):
return obj.to_dict()
return JSONEncoder.default(self, obj)
dumps = curry(dumps, cls=DjangoJSONEncoder)
and at last use this class to serialize my queryset.
def render_to_response(self, context, **response_kwargs):
return HttpResponse(dumps(self.get_queryset()))
This works quite well
Source: Stackoverflow.com