如何解决SqlAlchemy:如果不存在外键,为什么session.commit不会失败?
我对sqlAlchemy ForeignKey约束有误解。我的理解是,在下面插入B
应该引发ForeignKeyConstraint异常,因为没有A
作为其名称的"my_a"
。这不是ForeignKey约束的作用吗?是否要求约束表更新时约束映射的表列中存在该值?
from sqlalchemy import Column,create_engine,ForeignKey,Integer,VARCHAR
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class A(Base):
__tablename__ = 'table_A'
id = Column(Integer,primary_key=True)
name = Column(VARCHAR(32))
class B(Base):
__tablename__ = 'table_B'
id = Column(Integer,primary_key=True)
a_name = Column(VARCHAR(32),ForeignKey('table_A.name'),nullable=False)
engine = create_engine('sqlite:////tmp/AB.db.foo')
Base.Metadata.create_all(engine)
Session = sessionmaker()
Session.configure(bind=engine)
b = B(a_name="my_a")
session = Session()
session.add(b)
session.commit()
session.close()
解决方法
SQLite-即使是现代版本,默认情况下也不强制使用外键。
假设[SQLite]库在启用外键约束的情况下进行编译,则仍必须由应用程序在运行时使用PRAGMA foreign_keys命令启用它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。