'Overriding the table name in Flask-Alchemy

I am creating a Flask application and accessing the MySQL database using Flask-Alchemy.

I have following Class to access a table:

class price_table(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    trans_id = db.Column(db.Integer)
    timestamp = db.Column(db.Integer)
    order_type = db.Column(db.String(25))
    price = db.Column(db.Numeric(15,8))
    quantity = db.Column(db.Numeric(25,8))
    def __repr__(self):
            return 'id'

For the table 'price_table' this works brilliantly, but problem is I have a few tables with the same columns as 'price_table' from which I only know the name at runtime.

I want to reuse the class above so I thought I could change tablename to the name of the table I need to read, but that does not work, the program keeps reading the 'price-table'

How do I override the tablename at runtime?



Solution 1:[1]

You should use: __tablename__ :

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    email = Column(String(120), unique=True)

http://flask.pocoo.org/docs/0.12/patterns/sqlalchemy/

Solution 2:[2]

You can overwrite price_table.table.name attribute, yet keep in mind that it will affect your price_table model so, unless you want to use it to create a new specialized version of this table in the db and you are not interacting with price_table model - I wouldn't recommend that.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 metatoaster
Solution 2 Hemingway_PL