【问题标题】:Annotate via second-degree model relation通过二级模型关系进行注释
【发布时间】:2012-03-20 16:50:52
【问题描述】:

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

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

【问题讨论】:

    标签: python django


    【解决方案1】:

    使用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;
    

    【讨论】:

    • 头脑=被吹了。非常感谢!为什么这行得通,因为 Post 被键入到 UserProfile 而不是双下划线语法所暗示的相反方式?
    • 因为关系是这样工作的:school__userprofile__post。我们省略了 school__ 因为这是一个 School 查询集。 docs.djangoproject.com/en/dev/topics/db/queries/…
    猜你喜欢
    • 2016-06-17
    • 2011-05-05
    • 1970-01-01
    • 2015-03-09
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多