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

_set in Django for a queryset

What you are seeing is a reverse related object lookup. In your example: class Blog(models.Model): pass class Entry(..): blog = Blog(..) Now, given object e of type Entry, you would do e.blog to access the related object Blog – which is a forward relation. The _set is a reverse lookup class variable django puts in … Read more