我们在上一篇中说明了,如何在.net core的efcore中动态设置表名。
本文讲述如何在sqlalchemy中动态设置表名,使多个table可以对应到一个model
from sqlalchemy import create_engine,Column,BigInteger,String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
base = declarative_base()
engine = create_engine("postgresql://postgresadmin:[email protected]:32222/postgresdb")
class Test(base):
__abstract__ = True #
id = Column(BigInteger,primary_key=True)
name = Column(String(255))
tablename = Column(String(255))
def __repr__(self) -> str:
return self.tablename
session = sessionmaker(bind=engine)
Session = session()
# build a model class with a specific table name
def get_model(tablename,schema):
Model = type(tablename, (Test,), {
'__tablename__': tablename,
'__table_args__':{"schema":schema}
})
return Model
model = get_model('test1','test')
value = Session.query(model).all()
for item in value:
print(item)
上述demo包含三步