Django4 BuildingDataModel2
Django4 BuildingDataModel2
11
Common on_delete Options
We need to specify what will happen to the child if the parent is deleted using
on_delete option. Possible values:
• CASCADE: the associated child will be deleted.
• PROTECT: the data will be protected, and the parent will not be deleted
unless all referencing children are deleted first.
• SET_NULL: the child will not be deleted and the relative field referencing the
parent will be set to NULL (works only if the referencing field is nullable)
• SET_DEFAULT: the child will not be deleted and the relative field referencing
the parent will be set to a default value defined for the referenced field.
12 https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ForeignKey.on_delete
One-To-One Relationship
13 https://docs.djangoproject.com/en/4.1/topics/db/models/#one-to-one-relationships
A one-to-one relationship is similar to
a ForeignKey with unique=True, but the
"reverse" side of the relation will directly
Many-To-One Relationship return a single object. In contrast to
the OneToOneField "reverse" relation,
a ForeignKey "reverse" relation returns
a QuerySet.
14 https://docs.djangoproject.com/en/4.1/topics/db/models/#many-to-one-relationships
Many-To-Many Relationship
15 https://docs.djangoproject.com/en/4.1/topics/db/models/#many-to-many-relationships
Resolving Circular Relationship
Product
• Sometimes, classes can have multiple relationships.
title Category
• They can be both depending on each other.
description * 1
• A class can be the parent class in one relation and a price name
child class in the other relation. inventory
• To resolve this circular dependency, we can use the
name of the model (class) instead of referencing the 0 .. 1
model itself to define the related model while featured_product
creating the relationship field.
• we might need to also, define the related_name
option so we don’t have a conflict with the reversed
relation.
• use related_name = ‘+’ to tell Django to not create
the reversed relationship.
16
Representing Inheritance
17 https://docs.djangoproject.com/en/4.1/topics/db/examples/one_to_one/#one-to-one-relationships
https://docs.djangoproject.com/en/3.2/topics/db/models/#multi-table-inheritance