pllee
pllee

Reputation: 3959

JSON serialize Django Queryset with values being called. Is there anything wrong with my approach?

Here is the problem: Django's serializer doesn't support dictionaries and simplejson doesn't support Django Querysets. See JSON Serializing Django Models with simplejson

I was wondering if there is anything wrong with my solution. I have something like:

people = People.objects.all().values('name', 'id')
json.dumps(list(people))

I am still a newbie with Python/Django. Is casting the QuerySet to a list a bad idea? Is it more efficient to use the DjangoJSONEncoder suggested in the other topic?

Upvotes: 7

Views: 10390

Answers (1)

jfcalvo
jfcalvo

Reputation: 485

Your solution is totally valid and very clean in my own opinion.

If you need a list of lists (instead of a list of dictionaries) you can use too:

from django.utils import simplejson

people = People.objects.all().values_list('name', 'id')
simplejson.dumps(list(people))

Sometimes when the json output is very complex we usually use a json template with the *render_to_string* function, for example:

context = {'people': People.objects.all().values('name', 'id')}
render_to_string('templates/people.json', context, context_instance=RequestContext(request))

The template people.json could be:

[
 {% for person in people %}
    {"name": {{ person.name }}, "id": {{ person.id }} }
    {% if not forloop.last %} , {% endif %}
 {% endfor %}
]

But the use of templates is reserved for more complex cases than yours. I think that for easier problems a good solution is to use simplejson.dumps function.

Upvotes: 13

Related Questions