Hello, 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?
+2
A:
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 aSELECT 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.
Amarghosh
2010-05-25 08:31:58
thanks a lot, important to know!
apple_pie
2010-05-25 08:39:57