[Django]-Postgres doesn't respect Django's "on_delete = models.CASCADE" in models.py. Why?

5πŸ‘

βœ…

In short: Postgres does not handle the ON DELETE triggers. Django itself does the cascade handling.

Indeed, models.CASCADE is a callable that is called and collects other elements that needs to be deleted. We can for example look at the source code [GitHub]:

def CASCADE(collector, field, sub_objs, using):
    collector.collect(
        sub_objs, source=field.remote_field.model, source_attr=field.name,
        nullable=field.null, fail_on_restricted=False,
    )
    if field.null and not connections[using].features.can_defer_constraint_checks:
        collector.add_field_update(field, None, sub_objs)

Here the collector is thus a collection that collects objects that needs to be deleted.

So Django will when you delete an object, determine what other objects need to be deleted, updated, etc. and then make the queries in the correct order. It does not use any triggers in the database.

In fact you can implement your own deletion policy by implementing a callable that has the same parameters, and runs different logic, although I would advise to keep it simple.

If you want to let Django do the same, you should alter the field such that it looks like:

ALTER TABLE app_replyimage ALTER COLUMN reply_id
    integer REFERENCES orders ON DELETE CASCADE;

Leave a comment