Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过二次模型关系进行注释_Python_Django - Fatal编程技术网

Python 通过二次模型关系进行注释

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

我有以下(简化)模型:

我想做的是获得一份学校名单,注明每所学校的职位数量。出于许多原因,Post是外键输入到UserProfile的,而不是学校。我将如何使用Django ORM来执行此操作?我猜我必须使用annotate(),但当所讨论的两个模型没有外键直接关联时,它似乎不起作用。

用于:

将使用以下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;
用于:

将使用以下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;