'Refresh the metadata of a Base Class in SQLAlchemy

from core.Model import *
from core.Utils import Utils


class Role(Base, Model):
    # Roles
    ROOT = 1
    USER = 2

    __tablename__ = "role"
    __autoload_with__ = engine

    id = Column(BigInteger, primary_key=True, autoincrement=True)
    name = Column(String(30), nullable=False)
    created = Column(DateTime, default=Utils.time())
    updated = Column(DateTime, default=Utils.time(), onupdate=Utils.time())
    enable = Column(Boolean, default=True, nullable=False)

    formatters = {"created": Utils.date_formatter, "updated": Utils.date_formatter}

    @staticmethod
    def foo():
        from sqlalchemy import inspect
        table = inspect(Role)
        print("Before column insertion")
        print([column.name for column in table.c])

        # The add_column method executes a query and do a session.commit()
        # session.execute(sql_command)
        # session.commit()
        Role.add_column("test", Boolean)

        table = inspect(Role)
        print("After column insrtion")
        print([column.name for column in table.c])


Role.foo()

output of foo():

Before column insertion ['id', 'name', 'created', 'updated', 'enable'] Column added to table: role, column: test After column insrtion ['id', 'name', 'created', 'updated', 'enable']

I want to reload the metadata of the Role class after calling the add_column() method, so that the output of foo() be:

Before column insertion ['id', 'name', 'created', 'updated', 'enable'] Column added to table: role, column: test After column insrtion ['id', 'name', 'created', 'updated', 'enable', 'test']

Any help would be much appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source