Using a different schema for the same declarative Base in sqlalchemy

前端 未结 3 1969
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 07:52

I am new to both Pyramid and SQLAlchemy. I am working on a Python Pyramid project with SQLAlchemy. I have a simple model set up below. How would I go about being able to use

相关标签:
3条回答
  • 2021-02-01 08:14

    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.py
      class LoadTender(Base):
          __abstract__ = True
          id = ...
          def __repr__ ...
      
    2. Put a schema-specific Base in the hierarchy for each schema.

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

    0 讨论(0)
  • 2021-02-01 08:18

    just a guess

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

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

    0 讨论(0)
  • 2021-02-01 08:28

    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

    0 讨论(0)
提交回复
热议问题