Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

In Django doc,

select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query.

prefetch_related() does a separate lookup for each relationship and does the "joining" in Python.

What does it mean by "doing the joining in python"? Can someone illustrate with an example?

My understanding is that for a foreign key relationship, use select_related; and for M2M relationship, use prefetch_related. Is this correct?

1 Answer

0 votes
by (106k points)

The difference between select_related and prefetch_related in Django can be understand by below-mentioned code:-

class ModelA(models.Model):

pass 

class ModelB(models.Model):

a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() 

ModelA.objects.prefetch_related('modelb_set').all()

Browse Categories

...