简体   繁体   English

SqlAlchemy:如果外键不存在,为什么 session.commit() 不会失败?

[英]SqlAlchemy: why isn't session.commit() failing if foreign key doesn't exist?

I'm misunderstanding something about SqlAlchemy ForeignKey constraints.我对 SqlAlchemy ForeignKey 约束有一些误解。 My understanding is that the insertion of B below should raise a ForeignKeyConstraint exception because there's no A with "my_a" as its name.我的理解是,在下面插入B应该引发 ForeignKeyConstraint 异常,因为没有以"my_a"作为名称的A Isn't that what a ForeignKey constraint does?这不是 ForeignKey 约束的作用吗? Require the existence of the value in the table column mapped by the constraint when the constrained table is updated?更新约束表时要求约束映射的表列中存在值?

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 – even modern versions – does not enforce foreign keys by default. 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.假设 [SQLite] 库是在启用外键约束的情况下编译的,它仍然必须在运行时由应用程序使用 PRAGMA foreign_keys 命令启用。

SQLite documentation SQLite 文档

SQLAlchemy documentation SQLAlchemy 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM