1

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 and Reverse Foreign Key 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 and Reverse Foreign Key in Django?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129

2 Answers2

4
  • 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.name as shown below:

for obj in Product.objects.all():
    print(obj.category.name) # 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
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0

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.

Arif Rasim
  • 136
  • 2
  • 10