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:admin123@192.168.214.133: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)
- 在抽象模型类中定义表列
- 基于抽象模型构建一个模型类,并给它指定一个表名
- 像使用常规类一样使用构建的模型类。