2

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?

Harsh
  • 253
  • 1
  • 2
  • 10
  • did you check https://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view – Pabasara Ranathunga May 01 '18 at 06:58
  • @Pabasara Ranathunga That question is about concatenating list, I want to minimize round trip time by evaluating all querysets in single call. – Harsh May 01 '18 at 07:01
  • doesn't the q_list already gets evaluated? Try printing the length of each element in q_list – Pabasara Ranathunga May 01 '18 at 07:06
  • 1
    No, it doesn't. Here's is the small test: `from django.db import connection l = [a.objects.all()] print(len(connection.queries)) # Will print 0` – Harsh May 01 '18 at 07:13

1 Answers1

1

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.

James Bennett
  • 10,903
  • 4
  • 35
  • 24
  • I cannot use UNION as I am using django 1.8. Regarding the use case, I want to minimize the IO operations as the database may be present in the different machine connected via network. – Harsh May 01 '18 at 06:52
  • 2
    Many production Django deployments involve a database on a separate machine. While it's good to think about how to reduce query counts, trying to force a single query for everything is premature optimization; first, get your app running, then profile it and see where the performance hits are, and use things like caching or more efficient queries as your first resort. – James Bennett May 01 '18 at 07:30