Skip to content

Instantly share code, notes, and snippets.

@groovecoder
Created March 20, 2012 18:51
Show Gist options
  • Save groovecoder/2139696 to your computer and use it in GitHub Desktop.
Save groovecoder/2139696 to your computer and use it in GitHub Desktop.
monkey patch django loaddata to ignore foreign key checks
# monkey-patch django loaddata to ignore foreign key checks
from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
def uses_mysql(connection):
return 'mysql' in connection.settings_dict['ENGINE']
_old_handle = Command.handle
def _foreign_key_ignoring_handle(self, *fixture_labels, **options):
"""Wrap the the stock loaddata to ignore foreign key checks so we can load
circular references from fixtures.
This is monkeypatched into place in setup_databases().
"""
using = options.get('database', DEFAULT_DB_ALIAS)
commit = options.get('commit', True)
connection = connections[using]
if uses_mysql(connection):
cursor = connection.cursor()
cursor.execute('SET foreign_key_checks = 0')
_old_handle(self, *fixture_labels, **options)
if uses_mysql(connection):
cursor = connection.cursor()
cursor.execute('SET foreign_key_checks = 1')
if commit:
connection.close()
Command.handle = _foreign_key_ignoring_handle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment