Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
pllee Avatar asked Aug 12 '11 23:08

pllee


People also ask

How do I serialize Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

How does serialization work in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is defer in Django?

defer() and only() are somewhat opposite of each other. Both receives list of field_names . defer() will not query, list of columns, passed to it as argument. On Contrary to it, only() will query, only list of columns, passed to it as argument. Both are used in a scenario, where.


1 Answers

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.

like image 162
jfcalvo Avatar answered Sep 23 '22 18:09

jfcalvo