Dynamic Class Creation in SQLAlchemy

后端 未结 1 1150
有刺的猬
有刺的猬 2020-11-29 01:08

We have a need to create SQLAlchemy classes to access multiple external data sources that will increase in number over time. We use the declarative base for our core ORM mo

相关标签:
1条回答
  • 2020-11-29 01:48

    You can dynamically create MyObject using the 3-argument call to type:

    type(name, bases, dict)
    
        Return a new type object. This is essentially a dynamic form of the 
        class statement... 
    

    For example:

    mydict={'__tablename__':stored['tablename'],
            '__table_args__':{'autoload':True},}
    
    MyObj=type(stored['objectname'],(Base,),mydict)
    print(MyObj)
    # <class '__main__.MyObject'>
    print(MyObj.__base__)
    # <class '__main__.Base'>
    print(MyObj.__tablename__)
    # my_internal_table_name
    print(MyObj.__table_args__)
    # {'autoload': True}
    
    0 讨论(0)
提交回复
热议问题