views:

33

answers:

1

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 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.

Amarghosh
thanks a lot, important to know!
apple_pie