12月29日:更新模型
我有三个模型如下:
class Job(models.Model):
job_number = models.CharField(max_length=20, primary_key=True)
class Project(models.Model):
job = models.ForeignKey(Job, null=True) # updated (null=True)***
source = models.ForeignKey(Source) # added***
class Task(models.Model):
project = models.ForeignKey(Project)
class Source(models.Model): # added***
blahblah...
我想获得任务的工作号码。如下所示:
job = Job.objects.all().select_related()
jobno = job[0].project.job.job_number
我不确定上面的查询会在多长时间内触及数据库。但我猜它会超过两倍,不是吗?
select_related
只能预先缓存2个表的外键到我的理解。在这种情况下,任何人都可以建议最佳做法来减少击中数据库的次数吗?
答案 0 :(得分:0)
select_related()
在一个查询中加入所有这三个模型:
>>> from app.models import Task
>>> task = Task.objects.all().select_related()[0]
>>> task.project.job.job_number
u'123'
>>> from django.db import connection
>>> len(connection.queries)
1
>>> connection.queries
[{u'time': u'0.002', u'sql': u'QUERY = u\'SELECT "app_task"."id", "app_task"."project_id", "app_project"."id", "app_project"."job_id", "app_job"."job_number" FROM "app_task" INNER JOIN "app_project" ON ( "app_task"."project_id" = "app_project"."id" ) INNER JOIN "app_job" ON ( "app_project"."job_id" = "app_job"."job_number" ) LIMIT 1\' - PARAMS = ()'}]
>>>
可读的SQL:
SELECT "app_task"."id", "app_task"."project_id", "app_project"."id",
"app_project"."job_id", "app_job"."job_number"
FROM "app_task"
INNER JOIN "app_project" ON ( "app_task"."project_id" = "app_project"."id" )
INNER JOIN "app_job" ON ( "app_project"."job_id" = "app_job"."job_number" )
答案 1 :(得分:0)
您可以使用过滤器:
task = Task.objects.all().select_related().filter(
project__id__isnull=False,
job__id__isnull=False)