简体   繁体   English

Flask-SQLAlchemy中的多个相同表

[英]Multiple Identical Tables in Flask-SQLAlchemy

I'm creating a REST-like API to get data in and out of a legacy database. 我正在创建一个类似REST的API,以将数据输入和输出旧数据库。 At the moment I don't have the option to alter the db structure. 目前,我没有选择更改db结构的选项。 Nearly every table in the database has the exact same structure. 数据库中几乎每个表都具有完全相同的结构。 Here's how I'm currently handling it using Flask-SQLAlchemy: 这是我目前使用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? 有没有一种方法可以为从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? 如果存在,是否会导致外键问题,在ForeignTableClass中我必须在哪里将id定义为上面列出的每个表的外键?

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. 使用MetedataTable.tometadata()方法可能有更Python /优雅的方法来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM