我有以下(简化)模型:
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)
我想做的是获取一份学校清单,并注明每所学校的职位数量。出于多种原因,Post是外键键入UserProfile而不是School。我将如何使用Django ORM进行此操作?我猜我必须使用annotate(),但是当有问题的两个模型与外键没有直接关联时,它似乎不起作用。
答案 0 :(得分:1)
使用lookups that span relationship与Generate aggregates for each item in a QuerySet:
from django.db.models import Count
School.objects.annotate(post_count=Count('userprofile__post'))
将使用这样的sql:
SELECT "testapp_school"."id", "testapp_school"."name", COUNT("testapp_post"."id") AS "post_count" FROM "testapp_school" LEFT OUTER JOIN "testapp_userprofile" ON ("testapp_school"."id" = "testapp_userprofile"."school_id") LEFT OUTER JOIN "testapp_post" ON ("testapp_userprofile"."id" = "testapp_post"."profile_id") GROUP BY "testapp_school"."id", "testapp_school"."name", "testapp_school"."id", "testapp_school"."name" LIMIT 21;