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?
len() will fetch all the records and iterate over them. count() will perform an SQL COUNT operation (much faster when dealing with big queryset).
To simply check the length of a string in Django, you can use the len() function. This function takes a string input and returns an integer value i.e. the length of a string. You can use the len function as shown below in the below example. I am executing the code in the Django shell.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
Use count()
:
>>> Model.objects.count() 42 >>> Model.related_set.count() 102 >>> Model.related_set.filter(blah=42).count() 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With