【问题标题】:Foreign key constraints in SQLAlchemySQLAlchemy 中的外键约束
【发布时间】:2011-08-30 21:54:13
【问题描述】:

我正在使用 SQLAlchemy 的 ORM 端,并且我已经定义了我的一个列与另一个模型具有外键关系,使用:

Base = declarative_base()
class Model1(Base):
    __tablename__ = 'm1'
    Name = Column(String, primary_key = True)
    info = Column(String)

class Model2(Base):
    __tablename__ = 'm2'
    Name = Column(String, primary_key = True)
    info = Column(String)
    other_model = Column(String, ForeignKey('m1.Name'))

然而,我在other_model 属性中添加了什么似乎并不重要,将它提交到数据库似乎更开心,即使没有具有NameModel1 实例。

【问题讨论】:

  • 您可能还必须使用relation 工厂定义关系。
  • @sayap 使用 SQLite,@Keith 感谢领导,我会试一试
  • 看起来可能是 sqlite 的问题。我没有意识到,但显然 sqlite 不支持外键约束......或者至少没有,@ 987654321@。我会安装一个新版本,看看会发生什么

标签: python sqlalchemy


【解决方案1】:

看起来答案在我使用的数据库 (SQLite) 中,而不是 SQLAlchemy。 SQLite 版本

因此答案与this answer on foreign keys and SQLAlchemy 非常相似。

当我使用 Windows 时,我可以转到 the pysqlite2 page,打包的安装程序有版本 3.7.6.2 sqlite,然后最终的实现得到了 this SQLAlchemy page on sqlite engines and dialects 的帮助。这个SO question 也与升级过程有关。

最后,SQLite 引擎在决定是否强制执行外键约束时有点喜怒无常,this SO question 在强制执行外键时非常有用。

【讨论】:

    猜你喜欢
    • 2018-03-05
    • 1970-01-01
    • 2012-01-13
    • 2018-02-19
    • 2021-12-04
    • 2022-12-21
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    相关资源
    最近更新 更多