Reputation: 365
I have two models:
class FirstTable(models.Model):
name = models.CharField(...)
class SecondTable(models.Model):
examples = models.ManyToManyField(FirstTable)
I have a function which counts how many times FirstTable
is used in SecondTable's examples field:
data = {}
for i in FirstTable.objects.all():
data[i.name] = SecondTable.objects.filter(examples__exact=i).count()
but is it possible to get the same data with one request? (aggregate or annotate ways)
Upvotes: 0
Views: 31
Reputation: 5669
You can do:
from django.db.models import Count
FirstTable.objects.annotate(examples_count=Count('secondtable')).values('name', 'examples_count')
The output will be:
<QuerySet [{'name': 'Name1', 'examples_count': 3}, {'name': 'Name2', 'examples_count': 10}, ..., >
Upvotes: 1