我正在尝试在 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 sqlalchemy和 http://pythonhosted.org/Flask-SQLAlchemy/binds.html在我看来,好像我做对了。是什么赋予了?
最佳答案
您定义了一个对象 db = SQLAlchemy(app)
- 它是 Database1。你到处都提到它,但没有提到Database2。另请注意,代码使用 2 个部分标识符引用连接的列:
Account . AccountId and Accounts . id
而您希望拥有 3 个部分标识符:
Billing . Account . AccountId and [Accounts] . Accounts . id
您在每个类的定义中缺少 db name 的此属性:
__table_args__ = {'schema': 'Accounts'}
__table_args__ = {'schema': 'Billing'}
关于join - Flask-SQLAlchemy 中的跨数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16567448/