Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to set foreign key checks to 0

Ok so i'm migrating database from sqlite to mysql , i had few errors but i already resolved them. Now i have problem with this option because i don't know how to disable it. I tried

DATABASES = {

 'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'slave',                     
    'USER': 'root',                     
    'PASSWORD': 'root',                 
    'OPTIONS': {
                "init_command": "SET foreign_key_checks = 0;",
           },
    'HOST': '',                    
    'PORT': '',                      
   }
}

But it doesn't works and i don't know why.

Ofc i use json files to migration

python manage.py dumpdata --indent 2 --natural > dump.json
python manage.py loaddata dump.json

When I'm loading data on begining i can see:

SET SQL_AUTO_IS_NULL = 0
SET foreign_key_checks=0

But after some time:

SELECT (1) AS `a` FROM `xxx` WHERE `xxx`.`id` = 8  LIMIT 1
SET foreign_key_checks=1

And then i see exception. Traceback isn't important because it is connected with foreignkeys you can read more here

http://coffeeonthekeyboard.com/django-fixtures-with-circular-foreign-keys-480/

I know that i need to disable this option.

I tried :

http://djangosaur.tumblr.com/post/7842592399/django-loaddata-mysql-foreign-key-constraints

But like i said it doesn't work.

Can someone help...

like image 887
Silwest Avatar asked Apr 03 '13 17:04

Silwest


People also ask

How do you set a foreign key to check 0?

You can disable foreign key check in MySQL by setting the system variable foreign_key_checks to 0. However, please note, after you enable foreign key checks, MySQL will not re-validate your existing data that you added after disabling foreign key check. It will only check any new additions/updates to your database.

How do you ignore foreign key constraints?

To disable a foreign key constraint for INSERT and UPDATE statements. In Object Explorer, expand the table with the constraint and then expand the Keys folder. Right-click the constraint and select Modify. In the grid under Table Designer, select Enforce Foreign Key Constraint and select No from the drop-down menu.

How do I disable foreign key check in phpmyadmin?

From the Export tab, select the "Custom" export method. In the "Format-specific options:" area, look for and check "Disable foreign key checks".


1 Answers

you can put this at the end of your settings.py:

import sys
if 'loaddata' in sys.argv:
    # only change this for loaddata command.
    DATABASES['default']['OPTIONS'] = {
       "init_command": "SET foreign_key_checks = 0;",
    }
like image 139
dnozay Avatar answered Sep 29 '22 11:09

dnozay