4
votes

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

3
What you said is correct. Django emulates ON DELETE CASCADE. It doesn't use this feature of your DBMS. Django will issue the necessary delete statements to remove related models. Not sure why you're seeing that issue in the admin. - Michael Mior

3 Answers

6
votes

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.

2
votes

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.

1
votes

Django does cascade by default. I'm not really sure why you're getting an ON DELETE RESTRICT. Django 1.3 does let you select alternate ON DELETE procedures (using the on_delete kwarg when defining a field), and it's possible that if you inherited the codebase, someone might have done that previously and then removed it from the code, but neglected to update the database.

I would suggest altering the column manually to set it back to ON DELETE CASCADE. And simply move on from there. Like I said, this is something that the developer has to tell Django not to do; it cascades by default.