我对 SqlAlchemy ForeignKey 约束有些误解。我的理解是,下面插入 B 应该会引发 ForeignKeyConstraint 异常,因为没有带 \' 的 A
我对 SqlAlchemy ForeignKey 约束有些误解。我的理解是,下面的插入 B
应该会引发 ForeignKeyConstraint 异常,因为其名称中没有 A
with "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()