Count('blah1')
will count the same number of items as Count('blah1__blah2')
, because you made a JOIN. Indeed the query looks like:
SELECT model.*, COUNT(blah1.id) + COUNT(blah2.id) AS counting
FROM model
LEFT OUTER JOIN blah1.parent = model.id
LEFT OUTER JOIN blah2.parent = blah1.id
COUNT
does not care about the values, or the values being duplicates, it only will not count NULL
s, but for the rest, COUNT(blah1.id)
and COUNT(blah2.id)
will probably be nearly identical.
You thus should count unique values for blah1
:
from django.db.models import Count
Model.objects.annotate(
counting=Count('blah1', distinct=True) +
Count('blah1__blah2')
).get(id=1).counting
Here we will thus only count the distinct blah1
objects.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…