Django的prefetch_related得到所有多对多对象
问题描述:
我与这件事挣扎:Django的prefetch_related得到所有多对多对象
我需要让所有的多对多的对象和想使用prefetch_related
这是我的模型的样本:
class Company(models.Model):
companyjobs = models.ManyToManyField(CompanyJob, related_name='jobs')
class CompanyJob(models.Model):
source = models.CharField(_('Source'), max_length=64, db_index=True)
这是我的尝试:
search_results = Company.objects.prefetch_related('companyjobs')
现在我要访问companyj obs对象。 我该怎么做?
答
您可以直接从公司模型类的任何实例访问companyjob,而无需prefetch_related
。
例如。
# .all() will get all elements and [0] will get the first
company = Company.objects.all()[0]
company.companyjobs
# this is actually a ManyToMany Manager
# you deal with it like any other manager so
for companyjob in company.companyjobs.all():
# all() will again get all items in company.companyjobs
# here you iterate over all companyjobs in that company
... # do what you must
现在,我们只有一家公司,并从那里开始所有的公司职位。
我们做django的方式会对数据库进行2次查询。
一个对公司和一个用于工作
prefetch_related
将“合并”这些查询到一个 所以我们得到了所有相关的工作,而获取公司从DB
这是很方便的,因为,如果您不使用prefetch_related
,您必须处理的公司数量越多,您就需要额外查询一次,才能为该公司的工作大幅度降低绩效。
更多的信息在这里:https://docs.djangoproject.com/en/1.7/ref/models/querysets/#prefetch-related
'result.companyjobs.all()'? – meshy 2015-02-05 19:56:05