Python 通过二次模型关系进行注释
我有以下(简化)模型: 我想做的是获得一份学校名单,注明每所学校的职位数量。出于许多原因,Post是外键输入到UserProfile的,而不是学校。我将如何使用Django ORM来执行此操作?我猜我必须使用annotate(),但当所讨论的两个模型没有外键直接关联时,它似乎不起作用。用于: 将使用以下sql:Python 通过二次模型关系进行注释,python,django,Python,Django,我有以下(简化)模型: 我想做的是获得一份学校名单,注明每所学校的职位数量。出于许多原因,Post是外键输入到UserProfile的,而不是学校。我将如何使用Django ORM来执行此操作?我猜我必须使用annotate(),但当所讨论的两个模型没有外键直接关联时,它似乎不起作用。用于: 将使用以下sql: SELECT "testapp_school"."id", "testapp_school"."name", COUNT("testapp_post"."id") AS "post_co
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;
用于:
将使用以下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\uuuuu UserProfile\uuuu Post。我们省略了school,因为这是一个school查询集。头脑=崩溃。非常感谢!既然Post被设置为UserProfile,而不是双下划线语法所暗示的那样,那么为什么这样做呢?因为这种关系是这样工作的:school\uuuuu UserProfile\uuuu Post。我们省略了school,因为这是一个school查询集。
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;