如何使用相同的表名为不同的绑定定义两个模型

时间:2016-03-28 17:03:43

标签: python flask sqlalchemy flask-sqlalchemy

我在Flask中使用多个数据库(<div class="col-sm-6 masonry-item"> <a href="<?php echo Url::to(['site/roompage']); ?>" class="product_item text-center"> <span class="product_photo bordered_wht_border"> <?php foreach (explode(';',rtrim($row['images'],';'),1) as $key_img => $value_img) { ?> <?php echo Html::img('@backend/web'.'/'.$value_img);?> <?php } ?> </span> <span class="product_title"><?php echo $row['room_type']; ?></span> <span class="product_price">Rs.<?php echo $row['rate']; ?></span> </a> </div> <?php endforeach; ?> db_1)绑定:

db_2

config.py

但是当我为现有数据库定义模型时(表SQLALCHEMY_DATABASE_URI = 'db_1-postgres-url' SQLALCHEMY_BINDS = { 'historic': 'db_2-postgres-url', } db_1.mytable

db_2.mytable

失败并出现以下错误:

class Model1(db.Model):
    __tablename__ = 'mytable'

class Model2(db.Model):
    __tablename__ = 'mytable'
    __bind_key__ = 'historic'

我尝试使用不同的基础词来定义它们:一个使用InvalidRequestError: Table 'mytable' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object. File "manage.py", line 9, in <module> File "myproject/run.py", line 56, in create_app File "/myproject/views.py", line 9, in <module> File "/myproject/historic_models.py", line 59, in <module> File "flask_sqlalchemy/__init__.py", line 609, in __init__ File "sqlalchemy/ext/declarative/api.py", line 55, in __init__ File "sqlalchemy/ext/declarative/base.py", line 88, in _as_declarative File "sqlalchemy/ext/declarative/base.py", line 103, in setup_mapping File "sqlalchemy/ext/declarative/base.py", line 131, in __init__ File "sqlalchemy/ext/declarative/base.py", line 394, in _setup_table File "sqlalchemy/sql/schema.py", line 398, in __new__ ,另一个使用flask-sqlalchemy

declarative_base

在这种情况下,我可以毫无错误地运行我的应用程序,但是当我为class Model1(db.Model): __tablename__ = 'mytable' from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine Base = declarative_base() engine = create_engine(SQLALCHEMY_BINDS.get('historic')) Base.metadata.bind = engine class Model2(Base): __tablename__ = 'mytable' __bind_key__ = 'historic' 编写查询时,它仍然会查询Model2而不是db_1.mytable

我尝试了来自this pull request的解决方案,但它确实有效,但由于它不在Flask-SQLAlchemy中,还有办法完成同样的事情吗?

0 个答案:

没有答案