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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With