[Answered ]-Django ORM: count a subset of related items

2πŸ‘

βœ…

However I would like someway to annotate the number of practices that a person attends for a specific club.

Let us see.

First, find the specific club.

club = Club.objects.get(**conditions)

Next, filter all Persons who have practiced at this club.

persons = Person.objects.filter(practicerecord__Practice__Club = club)

Now, annotate with the count.

q = persons.annotate(count = Count('practicerecord'))

Edit

I was able to successfully make this work in my test setup: Django 1.2.3, Python 2.6.4, Postgresql 8.4, Ubuntu Karmic.

PS: It is a Good Ideaβ„’ to use lower case names for the fields. This makes it far easier to use the double underscore (__) syntax to chain fields. For e.g. in your case Django automatically creates practicerecord for each Person. When you try to access other fields of PracticeRecord through this field you have to remember to use title case.

If you had used lower case names, you could have written:

persons = Person.objects.filter(practicerecord__practice__club = club)
#                                               ^^        ^^  

which looks far more uniform.

PPS: It is Count('practicerecord') (note the lower case).

0πŸ‘

I’m afraid that raw sql is the only option here. Anyway it’s not that scary and hard to manage if you put it to model manager.

Leave a comment