Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output Django queryset as JSON

I want to serialize my queryset, and I want it in a format as this view outputs:

class JSONListView(ListView):     queryset = Users.objects.all()      def get(self, request, *args, **kwargs):         return HttpResponse(json.dumps({'data': [['bar','foo','bar','foo'],['foo','bar','foo','bar']]}, indent=4), content_type='application/json') 

I simply don't know how to output the queryset instead of the manual data in the example.

I've tried

json.dumps({"data": self.get_queryset()}) 

and

serializers.serialize("json", {'data': self.get_queryset()}) 

but it wont work. What am I doing wrong? Do I need to make a custom JSON Encoder?

like image 631
user2232982 Avatar asked Apr 08 '13 08:04

user2232982


People also ask

How do you serialize a 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 Django get JSON data?

To receive JSON data using HTTP POST request in Python Django, we can use the request. body property in our view. to call json. oads with request.

What is Queryset in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


1 Answers

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse  def some_view(request):     data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable     return JsonResponse(data, safe=False)  # or JsonResponse({'data': data}) 

Or another approach with Django's built-in serializers:

from django.core import serializers from django.http import HttpResponse  def some_view(request):     qs = SomeModel.objects.all()     qs_json = serializers.serialize('json', qs)     return HttpResponse(qs_json, content_type='application/json') 

In this case result is slightly different (without indent by default):

[     {         "model": "some_app.some_model",         "pk": 1,         "fields": {             "name": "Elon",             "age": 48,             ...         }     },     ... ] 

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);
like image 74
Mark Mishyn Avatar answered Sep 17 '22 08:09

Mark Mishyn