[Fixed]-Django count related objects

21👍

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

6👍

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()
👤abcdn

5👍

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.

👤ivan

Leave a comment