from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class MyModel(Base):
__tablename__ = 'my_custom_table_name'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
#... 其它定义或使用...
# 动态修改表名
MyModel.__table__.name = 'my_new_table_name'
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class MyModel(Base):
__tablename__ = 'my_custom_table_name'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
我们可以定义其抽象类:
class MyModelCls(Base):
__abstract__ = True # 关键语句,定义所有数据库表对应的父类
__table_args__ = {"extend_existing": True} # 允许表已存在
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
然后通过函数返回class对象
def get_source_data_model_cls(cid, cid_class_dict={}):
if cid not in cid_class_dict:
cls_name = table_name = cid
cls = type(cls_name, (MyModelCls, ), {'__tablename__': table_name})
cid_class_dict[cid] = cls
return cid_class_dict[cid]