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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With