Using a different schema for the same declarative Base in sqlalchemy Using a different schema for the same declarative Base in sqlalchemy python python

Using a different schema for the same declarative Base in sqlalchemy


I think you need a different model for each schema. __abstract__ can make this less painful. This follows on to Paul Yin's answer...

  1. Define an __abstract__ LoadTender model, so you don't have to keep coding it.

    #base.pyclass LoadTender(Base):    __abstract__ = True    id = ...    def __repr__ ...
  2. Put a schema-specific Base in the hierarchy for each schema.

    #schema1.pyfrom base import LoadTenderPublicBase = declarative_base(metadata=MetaData(schema='public'))class LoadTender(PublicBase, LoadTender):    __tablename__ = 'load_tenders'
  3. Do the same for other schema.


You can have a base module in package model

app\    models\        base.py        schema1.py        schema2.py    views\    ...

declare Base in base.py, then import it to other schemas


just a guess

LoadTender.__table_args__["schema"] = "whatever"

Probably best to put it somewhere where your app configurator is creating the app