class ModelA(models.Model):
pass
class ModelB(models.Model):
a = ForeignKey(ModelA)
ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship
* django select_related and prefetch_related
* Prefetch_related and select_related functions in django
---------------------------------
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.
-------------------
Example
class A(models.Model):
pass
class B(models.Model):
a = ForeignKey(ModelA)
# Forward ForeignKey relationship
A.objects.select_related('a').all()
# Reverse ForeignKey relationship
A.objects.prefetch_related('modelb_set').all()
# Use the magic syntax with "*" to expand the list
Knight.objects.all().prefetch_related(*selected_attributes)
django select_related and prefetch_related
select_related >> foreignkey
prefetch_related >> many to many
basically they are performance boosters ,used to avoid multiple unnecessary queries
Both methods achieve the same purpose, to forego unnecessary db queries.
But they use different approaches for efficiency..