[英]Foreign key constraints in SQLAlchemy
I'm using the ORM side of SQLAlchemy, and I've defined one of my columns to have a foreign key relation to another model, using: 我正在使用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'))
However, it doesn't seem to matter what I put in the other_model
attribute, it seems more than happy to commit it to the database, even if there is no Model1
instance that has that Name
. 但是,我将其other_model
属性中并不重要,即使没有具有该Name
Model1
实例,它似乎也很乐意将其提交到数据库。
It looks like the answer was in the database I was using (SQLite), not SQLAlchemy. 看起来答案是在我使用的数据库(SQLite)中,而不是SQLAlchemy。 SQLite versions <3.6.1 (AFAIK) do not support foreign key constraints. SQLite版本<3.6.1(AFAIK)不支持外键约束。
The answer is therefore very similar to this answer on foreign keys and SQLAlchemy . 因此,答案非常类似于外键和SQLAlchemy的答案 。
As I'm using Windows, I was able to go to the pysqlite2 page , the packaged installers have version 3.7.6.2 sqlite, and then and the final implementation was aided by this SQLAlchemy page on sqlite engines and dialects . 当我使用Windows时,我能够访问pysqlite2页面 ,打包的安装程序具有版本3.7.6.2 sqlite,然后最终实现由sqlite引擎和方言上的SQLAlchemy页面辅助。 This SO question is also relevant with regards to the upgrade process. 这个问题也与升级过程有关。
Finally, the SQLite engine is a bit temperamental when deciding whether or not to enforce the foreign key constraint, and this SO question is quite useful in forcing the foreign key enforcement. 最后,在决定是否强制执行外键约束时,SQLite引擎有点气质, 这个SO问题在强制执行外键时非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.