How can I temporarily disable a foreign key check in MySQL?

I’m dealing with two Django models that refer to each other through foreign keys. When I attempt to remove entries from these models, I encounter errors due to the foreign key constraints.

Here’s the code I’m using:

cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed()  # foreign key constraint error occurs here

cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()

The deletions do not work because of the foreign key relationships. Is there a way to temporarily disable these checks in MySQL so that I can remove the records without encountering these errors? I need to clear out some test data, but the dependencies are stopping me.

u can turn off foreign key checks for a bit: use SET FOREIGN_KEY_CHECKS=0; b4 the deletes, then turn it back on with SET FOREIGN_KEY_CHECKS=1; when done. really helpful for cleaning up test data! just remember to re-enable it!

You could also change your deletion order instead of turning off constraints completely. Delete the child records first, then the parents. But if you really need to disable foreign key checks, wrap everything in a transaction. Start with SET FOREIGN_KEY_CHECKS = 0, do your deletions, then SET FOREIGN_KEY_CHECKS = 1 before committing. This way if something breaks, you won’t mess up your data integrity. I use this all the time when clearing test environments - lets you bypass constraints temporarily while keeping everything consistent overall.

You could also use CASCADE options in your foreign key definitions if you can modify the schema. But since you’re working with existing Django models, just disable checks temporarily - that’s the fastest fix. I run the SQL commands directly through Django’s connection: connection.cursor().execute("SET FOREIGN_KEY_CHECKS=0") before deletions, then flip it back on after. Just watch your deletion order and always test on dev data first. Bypassing constraints can hide real data integrity problems if you’re not careful what you’re deleting.