Я хочу динамически добавлять столбцы в таблицу в моей базе данных, поскольку мне не нужно указывать все столбцы / атрибуты при настройке в классе sqlalchemy.
Я использую ORM с Declarative_base и введите для динамического добавления столбцов:
Declarative_base
engine = create_engine(DATABASE_URL_dev)
Base = declarative_base(engine)
class list_class1(Base):
__tablename__ = "test1"
id = Column(Integer, primary_key=True)
list = Column(String)
тип
attr_dict = {'__tablename__': 'test1', 'firstcolumn' : Column(Integer)}
secondcolumn = 'secondcolumn'
thirdcolumn = 'thirdcolumn'
attr_dict[secondcolumn] = Column(Integer)
attr_dict[thirdcolumn] = Column(Integer)
myclass = type('list_class1', (Base,), attr_dict)
Хотя при запуске это привело к следующей ошибке:
"sqlalchemy.exc.InvalidRequestError: Table 'test1' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object."
Я попытался добавить "__table_args__ = ({'extend_existing': True)"
в __tablename__
в list_class1, но проблема продолжалась.
Затем я попытался использовать stored
в attr_dict и type , как показано ниже:
attr_dict = {'__tablename__': stored['test1'],'__table_args__':{'autoload':True},}
firstcolumn = 'firstcolumn'
attr_dict[firstcolumn] = Column(Integer())
myclass = type(stored['test1'], (Base,), attr_dict)
Это привело к ошибке со следующим в последней части ошибки трассировки:
attr_dict = {'__tablename__': stored['test1'],'__table_args__':{'autoload':True},}
NameError: name 'stored' is not defined
Вопрос
Как решить эту проблему, чтобы добавить столбец к существующей таблице в SQLalchemy, не получая указанные ошибки.