是否动态设置__tablename__以在SQLAlchemy中进行分片? [英] Dynamically setting __tablename__ for sharding in SQLAlchemy?
问题描述
为了处理不断增长的数据库表,我们对表名进行了分片.因此,我们可以将数据库表命名为:
In order to handle a growing database table, we are sharding on table name. So we could have database tables that are named like this:
table_md5one
table_md5two
table_md5three
所有表都具有完全相同的架构.
All tables have the exact same schema.
我们如何使用SQLAlchemy并为与此对应的类动态指定表名?看起来declarative_base()类需要预先指定 tablename .
How do we use SQLAlchemy and dynamically specify the tablename for the class that corresponds to this? Looks like the declarative_base() classes need to have tablename pre-specified.
最终将有太多表无法手动指定从父/基类派生的类.
There will eventually be too many tables to manually specify derived classes from a parent/base class. We want to be able to build a class that can have the tablename set up dynamically (maybe passed as a parameter to a function.)
推荐答案
好的,我们使用了自定义的SQLAlchemy声明,而不是声明性的声明.
OK, we went with the custom SQLAlchemy declaration rather than the declarative one.
因此我们创建一个动态表对象,如下所示:
So we create a dynamic table object like this:
from sqlalchemy import MetaData, Table, Column
def get_table_object(self, md5hash):
metadata = MetaData()
table_name = 'table_' + md5hash
table_object = Table(table_name, metadata,
Column('Column1', DATE, nullable=False),
Column('Column2', DATE, nullable=False)
)
clear_mappers()
mapper(ActualTableObject, table_object)
return ActualTableObject
其中ActualTableObject是映射到表的类.
Where ActualTableObject is the class mapping to the table.
这篇关于是否动态设置__tablename__以在SQLAlchemy中进行分片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!