Django Model Relations

Django models operate by default on relational database systems (RDBMS) and support relationships.

Emre Cevik
Python | Django & Rest

--

Django Follows the 3 model Relationships:

1- One-To-One Relationship
2- One-To-Many Relationship
3- Many-To-Many Relatiosnship

One-To-One Relationship (OneToOneField)

One record in a table is associated with one and only one record in another table.

- Car company can have only one CEO.
- CEO can work only one Car company.

For more information about one-to-one relationship, you can check :

One-To-Many Relationship (ForeignKey)

One record in a table can be associated with one or more records in another table.

- Car company can have one or more car model.
- Car model can only belong to one car company.

For more information about one-to-many relationship, you can check :

Many-To-Many Relationship (ManyToManyField)

Multiple records in a table are associated with multiple records in another table.

- Many car models can run on same fuel type.
- Car model can run on diffrent fuel types.

For more information about many-to-many relationship, you can check :

Polymorphic Relationship

With Django’s Generic Relation — Polymorphic One-To-Many

One record in a multiple table can be associated with one or more records in another table.

- Sony can be sound system of many car models
- Pioneer can be sound system of many car models
- Car model can have only one sound system (Sony or Pioneer)

With Django-Polymorphic Package

Polymorphic One-To-Many

One record in a multiple table can be associated with one or more records in another table.

- Sony can be sound system of many car models
- Pioneer can be sound system of many car models
- Car model can have only one sound system (Sony or Pioneer)

Polymorphic Many-To-Many

Multiple records in a multiple table are associated with multiple records in another table.

- 2WD can be drive wheel system of many car models
- 4WD can be drive wheel system of many car models
- Car model can have many drive wheel system (2WD or/and 4WD)

For more information about polymorphic relationship, you can check :

If you want to learn more about Django, do check out the documentation, and make sure to check out our articles!

--

--