[Django]-COUNT(id) instead of COUNT(*) in Django

2👍

Try using:

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

This will do this query:

select count(id) from MyModel

1👍

Try using an aggregate query:

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

0👍

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(*)

👤ahmed

Leave a comment