Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django does not honor ON DELETE CASCADE

This is my model:

class Subscriber(models.Model):
    ...
    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True)
    ...

This is the generated SQL, according to sqlmigrate (and to manual inspection of the database):

ALTER TABLE `myapp_subscriber` ADD CONSTRAINT `myapp_subscriber_tenant_id_b52815ee_fk_myapp_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `myapp_tenant` (`id`);

I was expecting something like this:

CREATE TABLE child (
    id INT,
    parent_id INT,
    INDEX par_ind (parent_id),
    FOREIGN KEY (parent_id)
        REFERENCES parent(id)
        ON DELETE CASCADE
) ENGINE=INNODB;

With the ON DELETE CASCADE.

MySql (MariaDB actually) complains when I delete:

SQL Error (1451): Cannot delete or update a parent row: a foreign key constraint fails

Which makes sense since there is no ON DELETE CASCADE clause.

Why is Django 2.1.5 not honoring the ON DELETE CASCADE clause?

like image 496
volingas Avatar asked Jan 26 '23 17:01

volingas


1 Answers

From the docs:

on_delete doesn’t create a SQL constraint in the database. Support for database-level cascade options may be implemented later

It will perform the cascade in Django itself, so if you delete a Tenant object using Django delete() your Subscriber object will also be deleted. But not if you do it in SQL.

like image 84
dirkgroten Avatar answered Feb 03 '23 15:02

dirkgroten