Dynamically setting __tablename__ for sharding in SQLAlchemy?

后端 未结 6 1556
我寻月下人不归
我寻月下人不归 2020-12-28 17:11

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_md5         


        
6条回答
  •  醉酒成梦
    2020-12-28 17:38

    you can write a function with tablename parameter and send back the class with setting appropriate attributes.

    def get_class(table_name):
    
       class GenericTable(Base):
    
           __tablename__ = table_name
    
           ID= Column(types.Integer, primary_key=True)
           def funcation(self):
            ......
       return GenericTable
    

    Then you can create a table using:

    get_class("test").__table__.create(bind=engine)  # See sqlachemy.engine
    

提交回复
热议问题