我正在尝试在 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。
在 sqlalchemy和http://pythonhosted.org/Flask-SQLAlchemy/binds.html中关注Cross database join之后,在我看来,好像我做对了。是什么赋予了?