MPL
MPL

Reputation: 396

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?

Upvotes: 3

Views: 12205

Answers (3)

Hemingway_PL
Hemingway_PL

Reputation: 21

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.

Upvotes: 0

Viach
Viach

Reputation: 508

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/

Upvotes: 14

MPL
MPL

Reputation: 396

Based on the comment left by jbub I found the following solution that does the trick just as needed.

from app import db

def ClassFactory(name):
    tabledict={'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(25,8)),
               'quantity':db.Column(db.Numeric(25,8)),}

    newclass = type(name, (db.Model,), tabledict)
    return newclass

Upvotes: 0

Related Questions