通过二阶模型关系进行注释



我有以下(简化的)模型:

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(),但当这两个模型没有通过外键直接关联时,它似乎不起作用。

使用跨越关系的查找为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;

最新更新