Using a different schema for the same declarative base in sqlalchemy

I am new to Pyramid and SQLAlchemy. I am working on a Pyramid Python project with SQLAlchemy. The following is a simple model. How could I use this with different circuits at runtime? This will be the PostgreSQL database database. Right now, β€œpublic” is hard-coded into a declarative base model. I would need the opportunity to use the same model with a different circuit. What is the best approach? If I did not miss this, the documentation in SQLAlchemy seemed confusing to me.

from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, BigInteger __all__ = [ "LoadTender" ] __all__.sort() Base = declarative_base() class LoadTender(Base): __tablename__ = "load_tenders" __table_args__ = {"schema": "public"} id = Column("pkey", BigInteger, primary_key=True) def __repr__(self): return "" % self.id 

EDIT: I seem to have solved my problem, I am updating a snippet to show what I did below.

 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, BigInteger __all__ = [ "LoadTender" ] __all__.sort() Base = declarative_base() class ClientMixin(object): __table_args__ = {"schema": "client_schema_name"} class LoadTenderMixin(object): __tablename__ = "load_tenders" id = Column("pkey", BigInteger, primary_key=True) def __repr__(self): return "" % self.id class ClientLoadTender(LoadTenderMixin, ClientMixin, Base): pass 
+6
source share
3 answers

I think you need a different model for each circuit. __abstract__ can make this less painful. This follows the answer of Paul Yin ...

  • Define the __abstract__ LoadTender model, so you don't need to code it.

     #base.py class LoadTender(Base): __abstract__ = True id = ... def __repr__ ... 
  • Place the base structure specific to the schema 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' 
  • Do the same for the other circuit.

+6
source

just guess

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

It is probably best to place it somewhere where your application configurator creates the application

0
source

You may have a base module in a package model

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

declare Base in base.py, then import it into other schemes

0
source

All Articles