Django 在不需要时加载父对象
Django loads parent object when it's not required
这是我的简化模型配置:
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")))
如您所见,有一个主题与任务(非抽象模型)一对多相关。 Quiz 是 Task 的继承者之一。我想 select 所有与特定主题相关的测验。我只需要测验自己的字段 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,)
为什么第一个返回所有需要的数据就执行第二个?
根据要求,作为答案发布:始终检查您没有引用其他模型。
这是我的简化模型配置:
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")))
如您所见,有一个主题与任务(非抽象模型)一对多相关。 Quiz 是 Task 的继承者之一。我想 select 所有与特定主题相关的测验。我只需要测验自己的字段 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,)
为什么第一个返回所有需要的数据就执行第二个?
根据要求,作为答案发布:始终检查您没有引用其他模型。