apple_pie
apple_pie

Reputation: 339

Doing a count over a filter query efficiently in django

Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's much more efficient to do the count without retrieving those rows like so "SELECT COUNT(*) FROM ...". Is there a way to do so in django?

Upvotes: 1

Views: 1266

Answers (1)

Amarghosh
Amarghosh

Reputation: 59451

I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count

This is wrong assumption. From Django query set API reference for count()

count() performs a SELECT COUNT(*) behind the scenes

In general, QuerySets are lazy -- the act of creating a QuerySet doesn't involve any database activity. You can stack filters together all day long, and Django won't actually run the query until the QuerySet is evaluated.

Upvotes: 3

Related Questions