Chapter 3. Django Models and Database

Django Models – Relationship Fields

Django Models – Relationship Fields
Tag:

As explained at the beginning of this chapter, the relational database has three types of relationships. Django handles the relationships using Relationship Fields.

One-To-Many relationship: ForeignKey

The One-To-Many relationship is the most frequently used relationship in the relational database. In this relationship, each record in one table can correspond to many records in another table, but not the other way around. In Django, this relationship is handled through the ForeignKey data field.

One-To-One relationship: OneToOneField

In the One-To-One relationship, each record in one table corresponds to one record in another table. In Django, this relationship is handled through OneToOneField. One-to-one relationship tables can be combined into one table, but there are reasons to separate tables from the data management point of view.

Many-To-Many relationship: ManyToManyField

In the Many-To-Many relationship, each record in one table can correspond to many records in another table, and vice versa. Usually, a many-to-many relationship between two tables is defined through an intermediary join table (associative entity). In Django, this relationship is handled through ManyToManyField. By connecting the two tables using ManyToManyField, Django automatically creates the intermediary join table.

As explained at the beginning of this chapter, the relational database has three types of relationships. Django handles the relationships using Relationship Fields.

One-To-Many relationship: ForeignKey

The One-To-Many relationship is the most frequently used relationship in the relational database. In this relationship, each record in one table can correspond to many records in another table, but not the other way around. In Django, this relationship is handled through the ForeignKey data field.

One-To-One relationship: OneToOneField

In the One-To-One relationship, each record in one table corresponds to one record in another table. In Django, this relationship is handled through OneToOneField. One-to-one relationship tables can be combined into one table, but there are reasons to separate tables from the data management point of view.

Many-To-Many relationship: ManyToManyField

In the Many-To-Many relationship, each record in one table can correspond to many records in another table, and vice versa. Usually, a many-to-many relationship between two tables is defined through an intermediary join table (associative entity). In Django, this relationship is handled through ManyToManyField. By connecting the two tables using ManyToManyField, Django automatically creates the intermediary join table.

Tag: