Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django eager loading in many to many

Those are many models

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) 

And I want to get FacultyMember with all related project and publication with eager loading.

I try some thing like following code

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

However it do not working.

How to join related field in django orm with eager loading.

like image 949
Muhammed Hasan Celik Avatar asked Oct 13 '15 07:10

Muhammed Hasan Celik


1 Answers

Manytomany uses prefetch_related;

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

Refer here https://docs.djangoproject.com/en/1.8/ref/models/querysets/#prefetch-related

like image 169
Geo Jacob Avatar answered Oct 17 '22 23:10

Geo Jacob