首页 > 解决方案 > Access dynamically created tables SQLAlchemy

问题描述

Following the Tutorial on this site: http://sparrigan.github.io/sql/sqla/2016/01/03/dynamic-tables.html. I was trying to create an table using type.The function below is located in a file called models.py in my app directory.

def dynamic_class(table_name, columns):
dyn_table=type(table_name, (Base,), columns)

return dyn_table

From a python shell, I was trying to create and access a dynamic class with the following steps:

from app.models import dynamic_class
attr_dict = {'__tablename__': 'testclass6','col1': db.Column(db.Integer, primary_key=True),'col2': db.Column(db.Integer)}
dynamic_class('Testclass6', attr_dict)
<class 'app.models.Testclass6'>

But, if I'm now trying to access this created class

Traceback (most recent call last): File "", line 1, in NameError: name 'Testclass6' is not defined

So my question is, how to access it?

Thank you, please be polite I'm new to programming :-)

标签: python-3.xflask-sqlalchemy

解决方案


推荐阅读