I have the following (simplified) models:
class School(models.Model):
name = models.CharField(max_length=128)
class UserProfile(models.Model):
school = models.ForeignKey(School)
class Post(models.Model):
profile = models.ForeignKey(UserProfile)
What I’d like to do is obtain a list of schools, annotated with the number of posts each school has. For a number of reasons, Post is foreign-keyed to UserProfile instead of School. How would I go about doing this using the Django ORM? I’m guessing I would have to use annotate(), but it does not seem to work when the two models in question are not directly related by a foreign key.
Use lookups that span relationship to Generate aggregates for each item in a QuerySet:
Will use such sql: