Multiple Identical Tables in Flask-SQLAlchemy

纵饮孤独 提交于 2019-12-23 06:04:43

问题


I'm creating a REST-like API to get data in and out of a legacy database. At the moment I don't have the option to alter the db structure. Nearly every table in the database has the exact same structure. Here's how I'm currently handling it using Flask-SQLAlchemy:

class MyDatasetBase(object):
    timestamp = db.Column('colname', db.Float, primary_key=True)
    val1 = db.Column(db.Float)
    val2 = db.Column(db.Float)
    val3 = db.Column(db.Float)
    fkeyid = db.Column(db.Integer)

    @declared_attr
    def foreigntable(self):
        return db.relationship('ForeignTableClass', uselist=False)

class Table1(MyDatasetBase, db.Model):
    __tablename__ = 'table1'

class Table2(MyDatasetBase, db.Model):
    __tablename__ = 'table2'

class ForeignTableClass(db.Model):
    __tablename__ = 'ForeignTable'
    id = db.Column(db.Integer, db.ForeignKey('table1.fkeyid'), db.ForeignKey('table2.fkeyid'), primary_key=True)
    name = db.Column(db.String)

This all works, but some of these datasets contain a lot of tables and I feel like there has to be a more efficient way to do a few of these things.

Is there a way to get around explicitly defining a class for each of the tables derived from MyDatasetBase? If there is, will that cause problems with the foreign key stuff, where in ForeignTableClass I have to define id as being a foreign key for every table listed above?


回答1:


one way to do that is to use type method :

names = ['table1', 'table2', 'table3']

for name in names:
    type(name.title(), (MyDatasetBase, db.Model), { '__tablename__' : name })
# generate <class 'flask_sqlalchemy.Table1'> ... 

There is maybe a more pythonic/elegant way to do that with the Metedata and Table.tometadata() method.



来源:https://stackoverflow.com/questions/22567092/multiple-identical-tables-in-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!