1. 程式人生 > >1452, 'Cannot add or update a child row: a foreign key constraint fails

1452, 'Cannot add or update a child row: a foreign key constraint fails

如果在使用Django Admin後臺新增使用者時出現報錯:

(1452, 'Cannot add or update a child row: a foreign key constraint fails (`mxproject`.`django_admin_log`, CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))')

這時候需要在setting檔案的databases中新增以下程式碼取消外來鍵檢查

'OPTIONS':{
        "init_command":"SET foreign_key_checks = 0;",

完整的就是:

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