3

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?

MPL
  • 384
  • 1
  • 4
  • 20
  • You might find this useful: http://stackoverflow.com/questions/2768607/dynamic-class-creation-in-sqlalchemy – jbub Nov 05 '13 at 22:12
  • Thanks jbub that was exactly what I needed. Answered my own question based on it. – MPL Nov 06 '13 at 08:58

3 Answers3

13

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/

metatoaster
  • 17,419
  • 5
  • 55
  • 66
Viach
  • 498
  • 4
  • 10
0

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
MPL
  • 384
  • 1
  • 4
  • 20
0

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.