TransWikia.com

Is it more efficent to assign a database query to a variable for a single view than to have multiple queries

Stack Overflow Asked by rfkid on November 10, 2021

If I want to count the number of people in a database several different ways, would it be more efficient to assign the initial People.objects.all() to a variable (version A below) than to query it each time.

Effectively, does Version A result in a single hit to the db, while Version B results in two?

Version A:

people_var = People.objects.all()
last_name_filter = people_var.filter(last_name='Doe').count()
first_name_filter = people_var.filter(first_name='John').count()

Version B:

last_name_filter = People.objects.filter(last_name='Doe').count()
first_name_filter = People.objects.filter(first_name='John').count()

One Answer

Effectively, does Version A result in a single hit to the db, while Version B results in two?

No, both will hit the database twice.

The People.objects.all() does not make a query. Indeed, QuerySet are lazy. That means that, unless you for example iterate over it, cal len(…) on it, etc., it does not perform the query on the database. It is thus basically a query that waits to be performed unless necessary.

Even if people_var = Person.objects.all() was performed - it is not, it would not mean that the .filter(…) functions would use that cache. Indeed, if you call .all(), or .filter(…) on a QuerySet, you make a new, unevaluated QuerySet.

Finally if you call .count() you do not make a QuerySet, it will thus result in making a SELECT COUNT(*) FROM … query. So here you make two individual queries that will each count the number of objects. Even if both queries are identical, Django will make two queries. It is possible that the database will answer the second query faster, but that will be the same in both scenarios.

Answered by Willem Van Onsem on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP