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?
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.
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.
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.
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:
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
);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