Summary: In this tutorial, you will learn the difference between OneToOneField and ForeignKey in Django with the help of the examples.

Difference between OneToOneField and ForeignKey

A OneToOneField in Django is used to create a one-to-one relationship between two models. If it defined on model A referring to model B, then it means that for each record in the model A, there will be one and only one related record in the model B.

A perfect example of this is the relation between a Person and Passport because a person can have only one passport, and each passport can belong to one and only one person.

In this case, you would define a OneToOneField on the Person model that points to the Passport model:

class Person(models.Model):
    name = models.CharField(max_length=255)
    passport = models.OneToOneField(Passport, on_delete=models.CASCADE)

class Passport(models.Model):
    passport_number = models.CharField(max_length=255)

Whereas a ForeignKey in Django is used to create a one-to-many relationship between two models. If it defined on model A referring to model B, then for each record in the model A, there can be one or many related records in the model B.

An example for this is the relation between a Publication and Book. A publication can publish many books under its name, and each book can belong to one Publication only.

In this case, you would define a ForeignKey on the Book model that points to the Publication model:

class Publication(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    publication = models.ForeignKey(Publication, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)

In summary, OneToOneField is used for one-to-one relationships, while ForeignKey is used for one-to-many relationships.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply