Does anyone know if there's a way to just select the number of rows matching a query in Django? I have a search I've written that splits results into sets of 40, but I'd like to display the total number of results as well. I could to something like len(Model.objects.filter(name__icontains=search)), but it seems like that would be grossly inefficient (since I'm assuming that would generate a "SELECT * FROM model" and then all of the resulting objects). Any suggestions?
+4
A:
There are two main ways to handle this:
- Use Django's count() QuerySet method — simply append count() to the end of the appropriate QuerySet
- Generate an aggregate over the QuerySet — Aggregation is when you "retrieve values that are derived by summarizing or aggregating a collection of objects." Ref: Django Aggregation Documentation
The links above are to the applicable sections of Django's documentation.
Matthew Rankin
2010-07-30 17:06:24
Thanks, aggregate did the trick. It's kind of strange; I had to do an aggregate(Count('id')).count() (counting my count?). I'm happy though as long as it's hopefully only pulling up a number though and not all of the data in the table.
Andrew
2010-07-30 17:17:31