#Why isn't my Django Model creating a ON DELETE CASCADE?

18 messages · Page 1 of 1 (latest)

austere field
#

For some reason my Database isn't adding the ON DELETE CASCADE

class Settings(models.Model):
    user = models.OneToOneField(
        User,
        on_delete = models.CASCADE
    )

If I delete a User its corresponding settings does not get deleted.

I checked the DDL for that table and it doesn't say ON DELETE CASCADE, using MySQL btw

exotic moss
#

Yes, on_delete is a Django-level thing and is not applied to the database.

austere field
#

How do I do so on the Database Level? Instead of just on the Django Level

exotic moss
#

It mentions that you have to manually add the ON DELETE constraint to the field.

#

That being said, if you're just starting, use models.CASCADE and let Django help you. It's much easier and will work fine in 99% of the cases.

austere field
#

Thank you I appreciate the help!

sacred sequoia
#

How you say it indicates that you are editing the database directly, not using the ORM. That is really not recommended, since, as you saw, Django-level constraints are not applied 🤔

spring kernel
#

For the sake of posterity

austere field
# spring kernel

Why wouldn't this happen by default? I though it was bad practice to have things like this NOT done on the database level. Can someone confirm or deny this. Is it perfectly okay to create projects where some logic is not enforced on the database level and instead its through the ORM?

sacred sequoia
#

The ORM has to support multiple databases. It would not be smart to support it in one database unless it could be supported in all databases with the same level of safety/stability.

austere field
#

Gotcha

spring kernel
spring kernel
#

Regarding, is it bad practice, there's obviously a lot of benefits to handling deletes in the database, performance being one of the biggest. But there are also a lot of benefits to having the control with the ORM. If the database is deleting records without the ORM explicitly issuing them it leaves a lot of opportunities for confusion and bugs around an object's state.

#

I do think you could argue that it's bad practice to handle cascading deletes in the ORM instead of the DB. Just like some argue it's bad practice to use an ORM at all 🤷

#

I think it's perfectly fine to leave it up to the ORM. But with the caveat that you should avoid making changes to the data in the database outside of the ORM.