以下是我的简化模型配置:
class Topic(Sortable):
course = SortableForeignKey(Course)
publish = models.BooleanField(default=False)
title = models.CharField(max_length=200)
text = models.TextField()
estimated_time = models.PositiveIntegerField(null=True, blank=True))
class Task(models.Model):
topic = models.ForeignKey(Topic)
class Quiz(Task):
questions = models.TextField()
def __unicode__(self):
return u'[#%s] %s: %s' % (self.id, self.topic.title, capitalize(_("quiz")))
正如您所看到的,有一个主题与Task(非抽象模型)一对多相关。测验是任务继承者之一。我想选择与特定主题相关的所有测验。我只需要测验自己的字段questions
及其task_ptr_id
- 无需主题数据。以下是我的发言:
Quiz.objects.only('task_ptr_id', 'task_ptr__topic_id', 'questions').filter(topic_id=topic_id)
当我执行它时,执行两个数据库查询:
(0.001) SELECT "website_task"."id", "website_task"."topic_id", "website_quiz"."task_ptr_id", "website_quiz"."questions" FROM "website_quiz" INNER JOIN "website_task" ON ( "website_quiz"."task_ptr_id" = "website_task"."id" ) WHERE "website_task"."topic_id" = 1 LIMIT 21; args=(1,)
(0.000) SELECT "website_topic"."id", "website_topic"."order", "website_topic"."course_id", "website_topic"."publish", "website_topic"."title", "website_topic"."text", "website_topic"."estimated_time" FROM "website_topic" WHERE "website_topic"."id" = 1 LIMIT 21; args=(1,)
如果第一个所需的数据都返回,为什么它会执行第二个?
答案 0 :(得分:1)
根据要求,发布作为答案:始终检查您是否未引用其他模型。