Django count related objects
How can I count related objects in Django (in less than N queries, where N is number of object).
To clarify, l开发者_运维技巧et's say I have tables A and B. Every B is connected to exactly one A. Approach I tried:
A.objects.select_related().filter(attr=val)
A[i].B_set.count()
Of course, for every A[i] I want to find out number of B objects Django executes one query.
So the question is - is there a way to optimize that?
I have not tried how many queries are executed, but the Django way should be using annotate()
. For example:
from django.db.models import Count
q = A.objects.select_related('B').annotate(num_B=Count('B'))
print A[0].num_B
I have to answer my own question :) If object of A is queried something like this:
A.objects.select_related().filter(atrr=val).annotate(n_b=models.Count('B'))
This creates very long query, but at least there is just one.
Since Django 2.0 Count()
aggregate function accepts filter
parameter, which allows applying additional restrictions on the related objects queryset.
Works like this:
A.objects.select_related().annotate(
total=models.Count('myrelated__pk', filter=Q(only_items='that-i-need'))
).all()
精彩评论