二次模型关系注记

2024-03-29 07:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: name模型modelmodelspostlengthmax学校
1条回答
网友
1楼 · 发布于 2024-03-29 07:53:51

使用lookups that span relationshipGenerate 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;

相关问题 更多 >