user1328021 user1328021 - 4 months ago 21
Python Question

How to count number of items in queryset without count()

I'd like to count the number of items returned in my queryset. For example

userdesigns = Design.objects.filter (desadder = user.id)


I'd like to get the number of object returned without using count().

The reason is that I'm trying to speed up performance and reduce the number of database queries that I perform and I noticed that using count() pings the database, which I don't want. Considering I already pulled the complete lets of userdesigns, shouldn't there be a way to just count the number of items stored in that returned queryset?

Answer

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