DEV Community

Ejikeme Blaise
Ejikeme Blaise

Posted on

A Deep Dive into Django Foreign Keys

The effect of Foreign keys cannot be overemphasized. In Django-ORM, use the Foreign keys if you want to map Many to One relationship, for example, an agent to handle many projects in a table. Foreign keys are also used as referenced keys with an integer used to map a specific task a user performs in the database.

Foreign keys are not the same as OneToOne field or ManyToMany field, querying them or mapping them in ORM is not entirely the same, though they share some similarities. NB: You must create and save an object instance first, say Project table (model) before you can assign a foreign key to it, if not a ValueError will be returned.

Attributes of Foreign keys mapping

ON_DELETE: In Django-ORM, the on_delete option determines how the deletion of referenced data will be handled by the database to maintain data integrity.

1) To delete projects in a table assigned to an agent, you need to set on_delete=models.CASCADE as part of foreign key constraints schema. This attribute makes sure that when the agent is deleted all the projects assigned to them in that table is deleted as well.

2) To delete an agent without deleting an assigned projects to him/her, you need to set on_delete=models.SET_NULL, null=True. Null must be set to True as part of its constraints, if not it won't work. For example: in our case your model == agent


Project(models.Model):

field = models.ForeignKey("YourModel", on_delete=models.SET_NULL, null=True)
Enter fullscreen mode Exit fullscreen mode

3) To put restriction on projects to delete while deleting the agent in the database, you need to set on_delete=models.RESTRICT.

4) To protect projects from being deleted while deleting the agent instance assigned to the project without any dependency which is used in some rare cases, you need to set on_delete=models.PROTECT.

So, PROTECT never deletes and raises error. But RESTRICT (introduced from Django 3.1) deletes in some cases, but not all.

I know you might be wondering, hey, what is the difference between PROTECT and SET_NULL right now? Are they not the same, the answer is no. Think of it this way as stated below.

SET_NULL lets the parent be deleted but keeps the child.

PROTECT never lets the deletion of a parent to the deletion of the child.

Conclusion:
Using different types of on_delete is really related to your design and your constraints on deleting your objects.

Thank you for reading my article! I hope you now understand their differences and when to use them in your schema design.

For more information:
https://lnkd.in/dqmKJpm3

python #django #django_restframework, #database #ORM #SCHEMA ,#python_developers #developerscommunity

Top comments (0)