python sqlalchemy動態(tài)修改tablename兩種實現(xiàn)方式
方式一
在Python的SQLAlchemy ORM中,您可以使用以下代碼動態(tài)地更改數(shù)據(jù)模型類的表名:
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)
#... 其它定義或使用...
# 動態(tài)修改表名
MyModel.__table__.name = 'my_new_table_name'在這個例子中,我們首先定義了一個名為MyModel的數(shù)據(jù)模型,并將其與my_custom_table_name表相關聯(lián)。然后,在必要時,我們可以通過訪問模型類的__table__屬性來動態(tài)地更改表名。
這是因為ORM框架本身會自動為每個數(shù)據(jù)模型類創(chuàng)建一個對應的Table對象,并將其存儲在該類的__table__屬性中。我們可以使用name屬性直接更新此對象的名稱,從而實現(xiàn)動態(tài)更改表名的目的。
請注意,動態(tài)更改表名可能會影響到您的應用程序的正確性和可維護性。因此,請考慮清楚是否真正需要這樣做,以及如何規(guī)劃數(shù)據(jù)庫模式的變化。
方式二
如果我們原先的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)
我們可以定義其抽象類:
class MyModelCls(Base):
__abstract__ = True # 關鍵語句,定義所有數(shù)據(jù)庫表對應的父類
__table_args__ = {"extend_existing": True} # 允許表已存在
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)然后通過函數(shù)返回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]
到此這篇關于python sqlalchemy動態(tài)修改tablename兩種實現(xiàn)方式的文章就介紹到這了,更多相關python sqlalchemy動態(tài)修改tablename內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python?ORM框架之SQLAlchemy?的基礎用法
- Python?flask?sqlalchemy的簡單使用及常用操作
- python flask sqlalchemy連接數(shù)據(jù)庫流程介紹
- Python+SQLAlchemy輕松實現(xiàn)管理數(shù)據(jù)庫
- Python SQLAlchemy簡介及基本用法
- 3個Python?SQLAlchemy數(shù)據(jù)庫操作功能詳解
- Python使用SQLAlchemy模塊實現(xiàn)操作數(shù)據(jù)庫
- Python?SQLAlchemy與數(shù)據(jù)庫交互操作完整指南
- Python?SQLAlchemy庫的實現(xiàn)示例
相關文章
python三種數(shù)據(jù)結構及13種創(chuàng)建方法總結
拿Python來說,數(shù)據(jù)結構的概念也是超級重要,不同的數(shù)據(jù)結構,有著不同的函數(shù),供我們調用,接下來,我們分別來介紹字符串、列表、字典的創(chuàng)建方法2021-09-09
帶你用Python實現(xiàn)Saga 分布式事務的方法
在這篇文章里,我們介紹了 SAGA 的理論知識,也通過一個例子,完整給出了編寫一個 SAGA 事務的過程,涵蓋了正常成功完成,異常情況,以及成功回滾的情況,需要的朋友參考下吧2021-09-09

