One-To-Many Relationship (ForeignKey)

Django Model Relations — 2

Emre Cevik
Python | Django & Rest
3 min readNov 2, 2020

--

Before learning about this, you may want to take a look at one-to-one relationship.

One-To-Many Relationship

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.

When creating new car model:

Create relation between Model and Car.

Create relation between Car and Model.

Django, by defaults gives you a default related_name which is the ModelName (in lowercase) followed by “_set”. In this case, It would be carmodel_set.

Retrieve Records :

From car model to car:

From car to car model:

Filter car models by car:

Filter cars by car models:

Delete Records :

When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument same as OneToOneField.

For more information about on_delete, you can check out our one-to-one article and django documentation :

Reverse Relationship :

related_name will be the attribute of the related object that allows you to go ‘backwards’ to the model with the foreign key on it.

You can access the “CarModel” instances that are related to your “Car“ instance by going car_instance.models.all(). You can no longer use carmodel_set.

related_query_name is for use in Django querysets. It allows you to filter on the reverse relationship of a foreign key related field.

When we try to assign the same model to one more than cars :

In the next part, we’ll learn many to many relations.

If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out part of this series!

--

--