在Flask-SQLAlchemy的相同类中使用不同的绑定 [英] Using different binds in the same class in Flask-SQLAlchemy

查看:182
本文介绍了在Flask-SQLAlchemy的相同类中使用不同的绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有多个数据库具有相同的表和列(但内部不同的数据)。很显然,我需要使用绑定来访问所有这些,但显然不是这样做的简单:

  class WhateverTable db.Model):
__tablename__ ='whatevertable'
whatever = db.Column(db.String(255))

def __init __(self,bind = None):
self .__ bind_key__ = bind

然后再打电话:

  WhateverTable(bind ='bind_key_here')。query.filter_by(whatever ='whatever')。first()

有没有办法轻松做到这一点?我已经尝试从一个表类继承,然后在那里定义绑定,而这个工作,它真的不可扩展。



编辑:这: Flask继承了多个表的类相同的数据库使用__bind_key__ 排序我想要的,但我不想有不同的类,因为如果我添加一个新的数据库,我将不得不创建一组新的类和关系。

解决方案

Flask-SQLAlchemy 2.1 在会话中增加了对绑定参数的支持,它应该做你想做的。


I currently have multiple databases with identical Tables and Columns (but different data inside). So clearly I need to use binds to access all of them, but it's apparently not as simple as doing this:

class WhateverTable(db.Model):
    __tablename__ = 'whatevertable'
    whatever = db.Column(db.String(255))

    def __init__(self, bind=None):
        self.__bind_key__ = bind

and then later calling:

WhateverTable(bind='bind_key_here').query.filter_by(whatever='whatever').first()

Is there a way I can do this easily? I've tried inheriting from a table class and then defining the bind there, and while that works, it really isn't scalable.

EDIT: This :Flask inherited classes of tables in multiple identical databases using __bind_key__ does sort of what I want, but I don't want to have different classes because if I ever add a new database, I'm going to have to create a new set of classes and relationships.

解决方案

Flask-SQLAlchemy 2.1 added support for a binds parameter on the session which should do what you want.

这篇关于在Flask-SQLAlchemy的相同类中使用不同的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆