Relational database design models the complex associations between real-world entities. Django provides expressive model relationship fields to enforce referential integrity across One-to-Many, Many-to-Many, and One-to-One relationships, complete with automated reverse lookup managers and cascade deletion policies.
on_delete)When the referenced parent object is deleted, on_delete determines the behavior on child rows:
on_delete Policy | Behavior | Best Use Case |
|---|---|---|
models.CASCADE | Automatically deletes all child records referencing the parent. | User comments or invoice line items. |
models.PROTECT | Raises ProtectedError and blocks deletion if children exist. | Deleting a Customer who has active orders. |
models.SET_NULL | Sets the foreign key column to NULL (requires null=True). | Deleting a department or optional category. |
models.SET_DEFAULT | Sets the foreign key to its configured default value. | Reassigning tickets to a default unassigned user. |
models.DO_NOTHING | Takes no action; causes database foreign key constraint failures. | Rarely recommended. |
related_nameThe related_name argument defines the reverse accessor name on the parent model:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Creating Models | Migrations & ORM Queries |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.