How to combine multiple querysets in Django?

Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost. from itertools import chain result_list = list(chain(page_list, article_list, post_list)) Using itertools.chain is faster than looping each list and appending elements one by … Read more

How to output Django queryset as JSON?

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 … Read more