In Python's SQLAlchemy ORM, you can use the following code to dynamically change the table name of the data model class:
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'
In this example, we first define a A data model named MyModel
and associate it with the my_custom_table_name
table. Then, if necessary, we can dynamically change the table name by accessing the __table__
attribute of the model class.
This is because the ORM framework itself will automatically create a corresponding Table object for each data model class and store it in the __table__
attribute of the class. We can use the name
attribute to directly update the name of this object to dynamically change the table name.
Please note that dynamically changing table names may affect the correctness and maintainability of your application. So consider whether you really need to do this and how to plan for database schema changes.
If our original class is this:
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)
We can define its abstract class:
class MyModelCls(Base): __abstract__ = True # 关键语句,定义所有数据库表对应的父类 __table_args__ = {"extend_existing": True} # 允许表已存在 id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer)
Then return the class object through the function
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]
The above is the detailed content of What are the implementation methods of dynamically modifying tablename in python sqlalchemy?. For more information, please follow other related articles on the PHP Chinese website!