Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset Execution

Tags:

python

django

In Django, does a Queryset execute a new SQL query to the database every time I filter the queryset down or parse a field from an object?

For example... if I execute:

a = test.objects.all()
a2 = a.filter(name='Alex')
a3 = a.filter(name='John')
a4 = a.filter(name='Steve')

Does this sequence send 4 queries to the database? Or does it just send 1, and then handle the filters within Python?

I'm trying to make as few queries as possible to the DB for speed purposes... and didn't know if this is actually creating more of a speed bottleneck?

Thanks.

like image 763
George Rodman Avatar asked Jan 01 '23 17:01

George Rodman


1 Answers

Django querysets are lazy. The following line won't cause any database queries.

a = test.objects.all()
a2 = a.filter(name='Alex')
a3 = a.filter(name='John')
a4 = a.filter(name='Steve')

Having said that, if you cause all four querysets to be evaluated (e.g. by using list, then you will do 4 separate queries.

a = list(test.objects.all())
a2 = list(a.filter(name='Alex'))
a3 = list(a.filter(name='John'))
a4 = list(a.filter(name='Steve'))

Databases are very fast. For this example, it's probably fine to let the database do all four queries. You could try to fetch the three names you want in one query, for example:

a_combined = a.filter(name__in=['Alex', 'John', 'Steve'])

but this will make your code more complicated. Django doesn't provide a way to do a filter() call in Python.

You might find the django-debug-toolbar useful to see what queries your views are doing.

like image 78
Alasdair Avatar answered Jan 12 '23 14:01

Alasdair