Reputation: 7986
I have the following model, and I need to find out how many OtherModel instances are pointing to the same MyModel instance.
class MyModel(models.Model):
int = models.SmallIntegerField()
class OtherModel(models.Model):
other_model = models.ForeignKey(MyModel, null=True, blank=True)
int = models.SmallIntegerField()
I can use a for-loop, but the performance is very bad. Is there any other way I can select all MyModel objects, and get the related count in one query?
for m in MyModel.objects.all():
count = self.othermodel_set.count()
Upvotes: 5
Views: 2056
Reputation: 25539
from django.db.models import Count
result = MyModel.objects.all().annotate(othermodel_count=Count('othermodel'))
Django doc about aggregation features.
Upvotes: 5