Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django not setting MySQL ON DELETE = CASCADE

I'm using Django 1.3 with the MySQL 5.5 database backend. My assumption was that Django by default emulates the ON DELETE CASCADE effect for related objects when building the database via syncdb. However, inspecting the database reveals that the ON DELETE property is in fact set to "RESTRICT". Is this a bug? As I'm unable to delete related records I keep getting the IntegrityError message in the djang-admin when deleting an object that has a related object.

Thanks

like image 893
Imran Azad Avatar asked Jan 18 '23 22:01

Imran Azad


2 Answers

Django emulates ON DELETE CASCADE in Python -- that's why is doesnt need it set on the database tables. In fact, setting RESTRICT might even make sense, since it means that you can't accidentally delete any related objects without being warned about it in the admin.

In your case, it seems like you may have foreign key constraints set up that Django doesn't know about -- or possibly you are trying to delete through raw SQL; I can't tell from your question.

If the issue is that you can't delete from the admin, or from the ORM, then you need to make sure that your models are defined correctly. django will take care of collecting the related objects and performing the cascade itself.

If the issue is that deletes don't work from raw SQL, then you will either need to manually delete the related objects first, or relax the SQL constraint -- in that case, changing it to cascade may be the right solution.

like image 84
Ian Clelland Avatar answered Jan 29 '23 15:01

Ian Clelland


It would seem that Django 1.3.1 for some reason fails to apply the ON DELETE CASCADE property to the table. It could possibly have something to do with the MySQL-python 1.2.3 interface running on Windows. The only other way to resolve this issue is via custom SQL.

like image 28
Imran Azad Avatar answered Jan 29 '23 17:01

Imran Azad