SQLAlchemy在删除有外键约束的记录时,外键约束未起作用,何解?

一、环境:pyqt5+python 3.7+SQLAlchemy 1.4.36+mysql 8.0

二、相关表结构如下:

class maintenanceZone(Base):
    __tablename__ = "maintenanceZone"  # 区域信息
    __table_args__ = {
        "mysql_engine": "InnoDB",
    }

    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    cityName = sa.Column(sa.String(100), nullable=False )
    countyName = sa.Column(sa.String(100), nullable=False)




class maintainerInfo(Base):
    __tablename__ = "maintainerInfo"  #人员信息
    __table_args__ = {
        "mysql_engine": "InnoDB",
    }

    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    userName = sa.Column(sa.String(100), unique=True, nullable=False, comment="人员姓名")
    userPhone = sa.Column(sa.String(20), unique=True, comment="人员联系电话")
    zoneID = sa.Column(sa.Integer(),
                       sa.ForeignKey("maintenanceZone.id", ondelete="RESTRICT", onupdate="CASCADE"), comment="区域ID")

    zoneinfo = relationship("maintenanceZone", backref=backref('maintainerInfo', order_by=id))

三、相关代码如下:

zoneOne = session.query(maintenanceZone).filter(maintenanceZone.cityName == old_city,maintenanceZone.countyName == old_country).one()
session.delete(zoneOne)
session.commit()

四、数据库engine代码如下:

dburl = "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(dbIni["user"], dbIni["password"],dbIni["host"], dbIni["port"], dbIni["db"])
engine = create_engine(
            url=dburl,
            max_overflow=0, 
            pool_size=5,
            pool_timeout=20,
            pool_recycle=-1,
        )

五、问题如下:

1、在mysql8.0中,通过sql语删除maintenanceZone表中记录时,会触发外键约束,提示无法删除;

2、在python代码中通过SQLAlchemy删除maintenanceZone表中同一记录时,没有任何提示,直接删除!

 

六、SQLAlchemy执行时反馈信息:

先执行update把maintainerInfo表中的记录置为Null,然后在maintenanceZone中删除了该记录。

2022-06-24 18:12:03,245 INFO sqlalchemy.engine.Engine [generated in 0.00021s] {'param_1': 19}
2022-06-24 18:12:03,249 INFO sqlalchemy.engine.Engine UPDATE `maintainerInfo` SET `zoneID`=%(zoneID)s WHERE `maintainerInfo`.id = %(maintainerInfo_id)s
2022-06-24 18:12:03,249 INFO sqlalchemy.engine.Engine [generated in 0.00021s] {'zoneID': None, 'maintainerInfo_id': 1}
2022-06-24 18:12:03,267 INFO sqlalchemy.engine.Engine DELETE FROM `maintenanceZone` WHERE `maintenanceZone`.id = %(id)s
2022-06-24 18:12:03,267 INFO sqlalchemy.engine.Engine [generated in 0.00016s] {'id': 19}
2022-06-24 18:12:03,268 INFO sqlalchemy.engine.Engine COMMIT

 

 

如何禁止SQLAlchemy在删除maintenanceZone表记录时的默认update操作?

 

 

 

python
SQLAlchemy
外键约束失效
2022-06-24 13:06:47
浏览
已于2022-6-24 18:37:58修改
收藏 0
回答 0
待解决
相关问题
Mysql怎么添加有知道吗?
1972浏览 • 1回复 待解决
IPC与RPC通信什么约束限制?
345浏览 • 1回复 待解决
HarmonyOS 监听输入框删除
208浏览 • 1回复 待解决
HarmonyOS ArkUI是否有约束布局?
328浏览 • 1回复 待解决
如何引用IDE工程har包
474浏览 • 1回复 待解决
Preferences不起作用
4207浏览 • 1回复 待解决
是否可以引用工程HAP包
1843浏览 • 1回复 待解决
hilogprivate参数不起作用
5930浏览 • 1回复 待解决