Saqib Ali
Saqib Ali

Reputation: 12585

What is the best way to get the count of the number of items in a Django queryset?

I am doing a Django query. I want to know how many MyModels there are that have myAttribute value of "X". This is how I am doing it:

len(MyModel.objects.filter(myAttribute="X"))

Is this the most efficient way to handle it? I am concerned that this unnecessarily gets more data from the database than I need and instead I should be using the Count() function. However, from examples I have seen posted I am unsure if I can combine Count() with filter(). Can someone please advise?

Upvotes: 0

Views: 86

Answers (1)

miikkas
miikkas

Reputation: 818

The most optimal way to just get the count is to use count():

MyModel.objects.filter(myAttribute="X").count()

Upvotes: 6

Related Questions