[英]sqlalchemy: create relations but without foreign key constraint in db?
由於sqlalchemy.orm.relationship()
已暗示該關系,因此我不想在db中創建約束。 我該怎么辦?
目前,我在進行Alembic遷移后手動刪除這些約束。
無需定義“模式”級別的ForeignKey
約束,而是創建自定義的外部條件 ; 通過您想為“外鍵”和使用哪些列primaryjoin
以relationship
。 您必須手動定義primaryjoin
因為:
默認情況下,此值是基於父表和子表(或關聯表)的外鍵關系計算的。
In [2]: class A(Base):
...: a_id = Column(Integer, primary_key=True)
...: __tablename__ = 'a'
...:
In [3]: class C(Base):
...: c_id = Column(Integer, primary_key=True)
...: a_id = Column(Integer)
...: __tablename__ = 'c'
...: a = relationship('A', foreign_keys=[a_id],
...: primaryjoin='A.a_id == C.a_id')
...:
也可以使用foreign()
在primaryjoin
內聯注釋外鍵:
a = relationship('A', primaryjoin='foreign(C.a_id) == A.a_id')
您可以驗證沒有為表c發出FOREIGN KEY
約束:
In [4]: from sqlalchemy.schema import CreateTable
In [5]: print(CreateTable(A.__table__))
CREATE TABLE a (
a_id INTEGER NOT NULL,
PRIMARY KEY (a_id)
)
In [6]: print(CreateTable(C.__table__))
CREATE TABLE c (
c_id INTEGER NOT NULL,
a_id INTEGER,
PRIMARY KEY (c_id)
)
警告:
請注意,在數據庫端沒有適當的FOREIGN KEY
約束,您可以以任何所需的方式將參照完整性破壞成碎片。 在ORM /應用程序級別存在關系,但是不能在數據庫中強制執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.