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

本文分析了在使用SQLAlchemy框架进行数据库操作时遇到的1452外键约束失败错误,并提供了解决方案,包括调整数据表创建顺序及设置字段可空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 报错

    sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`test1`.`#sql-1864_7
    5`, CONSTRAINT `#sql-1864_75_ibfk_2` FOREIGN KEY (`category`) REFERENCES `category` (`id`))')
    [SQL: ALTER TABLE article ADD FOREIGN KEY(category) REFERENCES category (id)]
    
  • 数据模型

    class Category(db.Model):
        id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
        type_name = db.Column(db.String(100), nullable=False)
        articles = db.relationship('Article', backref='category')
        
    class Article(db.Model):
        id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
        title = db.Column(db.String(100), nullable=False)
        content = db.Column(db.Text, nullable=False)
        pdatetime = db.Column(db.DATETIME, default=datetime.now)
     	#添加外键  
        category_id = db.Column(db.INTEGER, db.ForeignKey('category.id'), nullable=False)
    
  • 分析

    由于一张表是新建的 category表。没有数据。

    而在article中是有数据的。而且新增了一个字段category_id。而且还设置成不可以为空。

    所以。数据库肯定会给article表中 新增的段赋值。

    那么问题来了。由于我们设置外键约束 且不可为空,article中的category_id字段 势必会去引用 category中的id的值。但是category表中是没有数据的。所以导致 1452, 'Cannot add or update a child row: a foreign key constraint fails

  • 解决。

    1. 先不设置外键约束。创建好数据表 category。往里头设置一些数据。然后在去设置外键约束。
    2. 将article中的category_id 设置成可以为空。
    3. 将article中的category_id 设置默认值 default=xx.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值