[Django]-Filtering an evaluated QuerySet

7đź‘Ť

âś…

“As few database queries as possible” isn’t the right criterion. You want to also think about the amount of work done by those database queries, and the amount of data that’s transferred from the database to your Django server.

Let’s consider the two ways to implement what you’re after. Approach 1:

entries = myblog.entry_set.all()
num_of_entries = len(entries)
is_jolly = any(e.headline.startswith('Jolly') for e in entries)

Approach 2:

num_of_entries = myblog.entry_set.count()
is_jolly = Entry.objects.filter(blog=myblog, headline__startswith='Jolly').exists()

In approach 1 there’s a single database query, but that query going to be something like SELECT * FROM ENTRY WHERE .... It potentially fetches a large number of entries, and transmits all their content across the network to your Django server, which then throws nearly all that content away (the only field it actually looks at is the headline field).

In approach 2 there are two database queries, but the first one is a SELECT COUNT(*) FROM ENTRY WHERE ... which fetches just one integer, and the second is a SELECT EXISTS(...) which fetches just one Boolean. Since these queries don’t have to fetch all the matching entries, there are a lot more possibilities for the database to optimize the queries.

So approach 2 looks much better in this case, even though it issues more queries.

Leave a comment