【问题标题】:SqlAlchemy: why isn't session.commit() failing if foreign key doesn't exist?SqlAlchemy:如果外键不存在,为什么 session.commit() 不会失败?
【发布时间】:2021-02-24 22:16:46
【问题描述】:

我对 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 不强制执行外键。 SQLAlchemy 特定细节here.
  • 啊,谢谢戈德,就是这样。如果您将此作为答案而不是评论,我将接受并投票。非常感谢!

标签: python sqlite sqlalchemy foreign-keys


【解决方案1】:

SQLite——即使是现代版本——默认情况下不强制使用外键。

假设 [SQLite] 库是在启用外键约束的情况下编译的,它仍必须由应用程序在运行时使用 PRAGMA foreign_keys 命令启用。

SQLite documentation

SQLAlchemy documentation

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 2018-03-06
    • 2018-09-27
    • 1970-01-01
    • 2021-12-04
    • 2015-04-03
    • 2013-02-27
    • 2018-07-31
    相关资源
    最近更新 更多