我对 SqlAlchemy 外键约束有一些误解。我的理解是,下面插入 B
应该引发ForeignKeyConstraint 异常,因为没有 A
以 "my_a"
作为名称。这不是外键约束的作用吗?更新约束表时要求约束映射的表列中存在值?
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 – 即使是现代版本 – 默认情况下不强制执行外键。
Assuming the [SQLite] library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command.
关于python - 为什么 SQLAlchemy 不使用 SQLite 强制执行外键约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64811882/