Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

python - sqlalchemy: create relations but without foreign key constraint in db?

Since sqlalchemy.orm.relationship() already implies the relation, and I do not want to create a constraint in db. What should I do?

Currently I manually remove these constraints after alembic migrations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of defining "schema" level ForeignKey constraints create a custom foreign condition; pass what columns you'd like to use as "foreign keys" and the primaryjoin to relationship. You have to manually define the primaryjoin because:

By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).

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 keys can also be annotated inline in the primaryjoin using foreign():

a = relationship('A', primaryjoin='foreign(C.a_id) == A.a_id')

You can verify that no FOREIGN KEY constraints are emitted for table c:

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)
)

Warning:

Note that without a FOREIGN KEY constraint in place on the DB side you can blow your referential integrity to pieces any which way you want. There's a relationship at the ORM/application level, but it cannot be enforced in the DB.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...