Does on_delete=models.CASCADE applies bidirectionally?

Hello there, I have a question; on_delete=models.CASCADE applies bidirectionally?
I defined a Profile model with field;

    user = models.OneToOneField(User, on_delete=models.CASCADE)

Here is the full story. But experimented this.
When I delete an instance from User: it is also deleted from Profile.
However, when I delete an instance from Profile: it is not deleted from User.

Best Regards.

No, it doesn’t, and in my opinion, shouldn’t.

Quoting from the comments in the code at django/django/db/models/fields/related_descriptors.py at ca5cd3e3e8e53f15e68ccd727ec8fe719cc48099 · django/django · GitHub

One-to-one relations are asymmetrical, despite the apparent symmetry of the
name, because they’re implemented in the database with a foreign key from
one table to another.

A OneToOneField is a foreign key with the constraint that the foreign key is unique. (No other row can have a reference to the same object in the referenced model.)

The models.CASCADE option is defined as deleting the object containing the foreign key when the model instance being referenced is deleted.

If the model with the foreign key is deleted, it physically has no effect on the model being referenced. (There are no potential integrity constraint violations created by doing this.)

As a result of this, you do need to consider the “orientation” of one-to-one relationships when defining your models. In a “profile” situation, you may have cases where a “User” doesn’t have a related “Profile”, but you would never have a “Profile” in the absence of a “User”. In this type of situation, you want the “Profile” to have the OneToOneField referencing “User”.

1 Like

Ok. Thank you KenWhitesell.