Flask-SQLAlchemy中的跨数据库连接

时间:2013-05-15 14:13:08

标签: join sqlalchemy flask flask-sqlalchemy

我正在尝试在Flask-SQLAlchemy中进行跨数据库连接:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = '...Master...'
app.config['SQLALCHEMY_BINDS'] = { 'Billing': '...Billing...' }
db = SQLAlchemy(app)

class Account(db.Model):
    __tablename__ = 'Accounts'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(255))

class Setting(db.Model):
    __tablename__ = 'Settings'
    AccountId = db.Column(db.Integer, db.ForeignKey(Account.id), primary_key=True)
    Enabled = db.Column(db.Boolean)

class BillingAccount(db.Model):
    __tablename__ = 'Account'
    __bind_key__ = 'Billing'
    id = db.Column(db.Integer, primary_key=True)
    AccountId = db.Column(db.Integer, db.ForeignKey(Account.id))
    currency = db.Column(db.Integer)

class AccountSetting(db.Model):
    __table__ = db.join(Account, AccountSetting)
    id = db.column_property(Account.id, AccountSetting.AccountId)
    username = Account.username
    enabled = Setting.Enabled

class AccountSettingBilling(db.Model):
    __table__ = db.join(Account, AccountSetting).join(BillingAccount)

    id = db.column_property(Account.id, AccountSetting.AccountId, BillingAccount.AccountId)
    username = Account.username
    enabled = Setting.Enabled
    currency = BillingAccount.currency

有了这个,我可以成功查询AccountSetting.query.all()但不能成功查询AccountSettingBilling.query.all(),它失败并出现错误208(MSSQL表示'对象不存在')。

如果我检查生成的SQL,我可以清楚地看到它正在Account.AccountId = Accounts.id上进行JOIN,当我希望看到一些对Billing的引用,例如Billing.Account.AccountId = Accounts.id。

在关注Cross database join in sqlalchemyhttp://pythonhosted.org/Flask-SQLAlchemy/binds.html后,它看起来好像我已经做好了事情。是什么给了什么?

1 个答案:

答案 0 :(得分:1)

您定义了一个对象db = SQLAlchemy(app) - 它是Database1。你到处都提到它,但是没有对Database2的引用。另请注意,代码是指使用2部分标识符进行连接的列:

Account . AccountId and Accounts . id

而您希望有3个部分标识符:

Billing . Account . AccountId and [Accounts] . Accounts . id

您从每个类的定义中缺少此db属性的属性:

__table_args__ = {'schema': 'Accounts'}
__table_args__ = {'schema': 'Billing'}