![](/img/trans.png)
[英]django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails
[英]Cannot add or update a child row: a foreign key constraint fails on a Django generated MySQL table
我正在基于django的项目上工作,该项目创建了两个表table1
和table2
,并具有从table2
到table1
的外键。 我需要手动将一些值插入table2
。 在MySQL中尝试这样做时,出现约束失败错误。 我仔细检查过,表table1
已经存在外键约束所需的相应条目。 我调查了有关SO的先前问题,但找不到合适的解决方案。
表1架构:
+------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| email | varchar(100) | NO | | NULL | |
表2:
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| km | varchar(1000) | YES | | NULL | |
| owner_id | int(11) | NO | MUL | NULL | |
| receiver_id | int(11) | NO | MUL | NULL | |
+-------------+---------------+------+-----+---------+----------------+
insert语句insert into crest_recipient values(id,owner_id=5,receiver_id=5,km="hello world");
或类似的失败,并出现确切的错误,因为
无法添加或更新子行:外键约束失败(crest.crest_recipient CONSTRAINT crest_recipient_owner_id_4943116a1387be04_fk_crest_user_id FOREIGN KEY(owner_id)参考crest_user(id))
您正在尝试在子表crest_recipient中插入一行,该行在父表crest_user中不存在。
因此,首先在主表中插入相应的行,然后可以在子表中插入。
您正在尝试更新或插入一行crest.crest_recipient
表中,列中的值owner_id
在crest_user
列id
中不存在
使它看起来像这样
insert crest_recipient (km,owner_id,receiver_id) values ('test',5,1)
'test',5,1
是您想要的。
跳过ID列。 不指定它,不提供它的值。 它最有可能是auto_increment PK(基本上没有别的办法了)。 数据库引擎会为您选择它。 指定它只会使事情浪费99%的时间。
现在专注于参数2(5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.