Django渴望加载许多对很多

时间:2015-10-13 07:31:15

标签: django orm inner-join django-orm eager-loading

那些是很多型号

class FacultyMember(models.Model):
    # some attributes

class Publication(models.Model):
    # some attributes
    author = models.ManyToManyField(FacultyMember, blank=True)

class Project(models.Model):
    # some attributes
    researchers = models.ManyToManyField(FacultyMember, blank=True) 

我希望Faculty会员能够通过热切的加载获得所有相关的项目和出版物。

我尝试了一些像下面的代码

FacultyMember.objects.filter(
    pk=id,
    first_name=first_name,
    last_name=last_name
).select_related('project_set').select_related('publication_set')

然而它不起作用。

如何在django orm中加入相关字段并加载。

1 个答案:

答案 0 :(得分:11)

Manytomany使用prefetch_related;

FacultyMember.objects.filter(
pk=id,
first_name=first_name,
last_name=last_name
).prefetch_related('project_set').prefetch_related('publication_set')

请参阅此处https://docs.djangoproject.com/en/1.8/ref/models/querysets/#prefetch-related