Harsh
Harsh

Reputation: 253

Evaluate multiple querysets in a single db call

Lets suppose I have a list of unevaluated querysets:

q_list = [a.objects.all(), b.objects.all(),...]

I want to evaluate all of them at once in a single database call. I can iterate over the list and evaluate them individually like this:

evaluated_q_list = map(list, q_list)

But that will make multiple db queries. Is it possible to do this in a single db query using Django ORM?

Upvotes: 2

Views: 818

Answers (2)

Nishant Singh
Nishant Singh

Reputation: 21

This is something I made for Postgres https://github.com/iNishant/django-querysets-single-query-fetch

uses Postgres's json_build_object to execute multiple querysets over a single network call. We use it in production at https://mydukaan.io in one of our most critical paths 😃.

Upvotes: 0

James Bennett
James Bennett

Reputation: 11163

If what you want here is to combine two queries with the SQL UNION operation, Django supports that as a QuerySet method.

But it's not clear why you want to try to force this into a single query; more information about your use case would help in coming up with suggestions.

Upvotes: 1

Related Questions