我有以下型号:
Person 模型与 Questions 有多对多 (M2M) 关系。
class Person(models.Model):
name = models.CharField(max_length=100)
questions = models.ManyToManyField(Question, related_name='persons')
我从 Django 调试工具栏中看到,当我发出:
persons = Person.objects.filter(name="Foo").prefetch_related("questions")
它执行 2 个查询,一个到 Person 表,另一个到 Questions 表,但除外。
但是,如果我遍历模板中的列表,则会对 Person 的每一行进行额外的选择查询。
{% for person in persons %}
{{ person.name }}
{% for question in person.questions.all %}
{{ question.text }}
{% endfor %}
{% endfor %}
这是问题的第二个 SQL,所以预取肯定是有效的,但不知何故,它需要额外的查询来显示每个问题。
SELECT ("myapp_person_questions"."person_id") AS "_prefetch_related_val",
"myapp_question"."id", "myapp_question"."asker_id",
"myapp_question"."question", "myapp_question"."timestamp"
INNER JOIN "myapp_person_questions" ON ("myapp_question"."id" =
"myapp_person_questions"."question_id") WHERE
"myapp_person_questions"."person_id" IN (1, 2, 3, 4) ORDER BY
"myapp_question"."timestamp" DESC
SELECT "myapp_question"."id", "myapp_question"."asker_id",
"myapp_question"."question", "myapp_question"."timestamp" FROM
"myapp_question" INNER JOIN "myapp_person_questions"
ON ("myapp_question"."id" = "myapp_person_questions"."question_id")
WHERE "myapp_person_questions"."person_id" = 1 ORDER BY "myapp_question"."timestamp" DESC
我禁用了所有 custom Manager
,所以我很确定没有在QuerySet
.
需要注意的一件事是我自己没有明确生成连接表,这可能是问题吗?(使用through
)