[Fixed]-How to count number of items in queryset without count()

26👍

len(). A QuerySet is evaluated when you call len() on it. This, as you might expect, returns the length of the result list.

Note: Don’t use len() on QuerySets if all you want to do is determine the number of records in the set. It’s much more efficient
to handle a count at the database level, using SQL’s SELECT COUNT(*),
and Django provides a count() method for precisely this reason. See
count() below.

Source

So, if you call len(userdesigns) instead of userdesigns.count(), django will request all related data from the table in a single query. After that you can access all items of userdesigns variable, no additional queries will be made.

>>> m = Model1.objects.filter(desadder=1)
>>> len(m)
(0.000) SELECT "app1_model1"."id", "app1_model1"."desadder", "app1_model1"."test" FROM "app1_model1" WHERE "app1_model1"."desadder" = 1 ; args=(1,)
2
>>> m[0]
<Model1: Model1 object>
>>> m = Model1.objects.filter(desadder=1)
>>> len(m)
(0.000) SELECT "app1_model1"."id", "app1_model1"."desadder", "app1_model1"."test" FROM "app1_model1" WHERE "app1_model1"."desadder" = 1 ; args=(1,)
2
>>> m[0]
<Model1: Model1 object>
>>> 

0👍

Riateche answered this, but if you didn’t want to use len() or .count() directly on the QuerySet, you could return a values_list and use len() on it.

Django documentation says:

https://docs.djangoproject.com/en/dev/ref/models/querysets/

A ValuesQuerySet is useful when you know you’re only going to need
values from a small number of the available fields and you won’t need
the functionality of a model instance object.

I doubt this is any more speedy, but you could always time it and see. It could be useful if you only want to return a subset of the total available fields in a table.

Leave a comment