Issue with Foreign Key Relationship Across Schemas in SQLAlchemy and Alembic Migrations #1571
-
I’m trying to create a foreign key relationship between two models that are in different schemas in PostgreSQL using SQLAlchemy and Alembic. However, I’m encountering an error when trying to generate the Alembic migration for the foreign key, and I could use some guidance on what I’m doing wrong. Problem DescriptionI have two schemas: schema1 with a table model1 Models Setup model1.py defines Model1 in schema1. model1.py (Schema1)
model2.py (Schema2)
Alembic ConfigurationIn env.py, I’ve set up the target_metadata to include both Base1.metadata and Base2.metadata, like so:
Error
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
hi - you are using two separate from model1 import Model1
class Model2(Base2):
# ...
model1_id = Column(Integer, ForeignKey(Model1.id), nullable=False) |
Beta Was this translation helpful? Give feedback.
hi -
you are using two separate
MetaData
collections so there is no string lookup between those two. To retain the use of two separateMetaData
collections you need to apply the actual remoteColumn
object toForeignKey
: