What are "Forward Foreign Key (Relationship)" and "Reverse Foreign Key (Relationship)" in Django?
When reading the topics related to Django's select_related() and prefetch_related() on some websites including Stack Overflow, I frequently see the words Forward Foreign Key (Relationship) and Reverse Foreign Key (Relationship) but I couldn't find the definitions on Django Documentation:
# "models.py"
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=20)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
price = models.DecimalField(decimal_places=2, max_digits=5)
So, what are Forward Foreign Key (Relationship) and Reverse Foreign Key (Relationship) in Django?
Forward foreignKey is the Product models relation to the the Category model, where each product has to have a category. A reverse foreign key is the relation of the Category model to the Product model and a Category can have many Products as reverse foreignKey.
Forward Foreign Key means that the child model which has the foreign key to the parent model accesses the parent model.
Reverse Foreign Key means that a parent model accesses the child model which has the foreign key to the parent model.
So in your case, because Product
model has the foreign key to Category
model so Category
model is a parent model and Product
model is a child model as shown below:
# "models.py"
from django.db import models
class Category(models.Model): # Parent model
name = models.CharField(max_length=20)
class Product(models.Model): # Child model
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
price = models.DecimalField(decimal_places=2, max_digits=5)
<Forward Foreign Key>
The child model Product
accesses the parent model Category
with obj.category
as shown below:
for obj in Product.objects.all():
print(obj.category) # Here
<Reverse Foreign Key>
The parent model Category
accesses the child model Product
with obj.product_set.all()
as shown below:
for obj in Category.objects.all():
print(obj.product_set.all()) # Here