Django 渴望加载多对多

Django eager loading in many to many

这么多型号

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) 

并且我希望通过预加载获得所有相关项目和出版物的 FacultyMember。

我尝试了一些类似下面的代码

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

但是它不起作用。

如何通过预先加载在 django orm 中加入相关字段。

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