cansadadeserfeliz
cansadadeserfeliz

Reputation: 3133

COUNT(id) instead of COUNT(*) in Django

I'm paginating a list view for a model with many fields, so it takes a lot of time to execute MyModel.objects.filter('some filter').count(), because on SQL level it runs

SELECT COUNT(*) FROM mytable

instead of:

SELECT COUNT(id) FROM mytable

even if I write explicitly

MyModel.objects.only('id').count() 

How can I make Django run COUNT(id) on .count()?

Update:

I'm using PostgreSQL.

Upvotes: 5

Views: 4207

Answers (3)

Aadit Shah
Aadit Shah

Reputation: 46

Try using:

MyModel.objects.filter('some filter').values_list("id).count()

This will do this query:

select count(id) from MyModel

Upvotes: 2

ahmed
ahmed

Reputation: 5590

COUNT(id) is roughly the equivalent of:

MyModel.objects.exclude(id=None).count()

this will add extra step to count the table fields, which is not the case for COUNT(*)

Upvotes: 0

Exelian
Exelian

Reputation: 5888

Try using an aggregate query:

from django.db import models
MyObject.objects.all().aggregate(models.Count('id'))['id__count']

Upvotes: 2

Related Questions