Join 炼金术中的跨数据库连接
我正在尝试在Flask SQLAlchemy中进行跨数据库连接:Join 炼金术中的跨数据库连接,join,sqlalchemy,flask,flask-sqlalchemy,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
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进行连接,而我希望看到一些对账单的引用,例如Billing.Account.AccountId=Accounts.id
在我看来,我做的一切都是正确的。给出了什么?您定义了一个对象
db=SQLAlchemy(app)
-它是数据库1。您可以在任何地方引用它,但没有对数据库2的引用。另请注意,代码是指使用2个零件标识符进行连接的列:
Account . AccountId and Accounts . id
Billing . Account . AccountId and [Accounts] . Accounts . id
鉴于您希望有3个零件标识符:
Account . AccountId and Accounts . id
Billing . Account . AccountId and [Accounts] . Accounts . id
您在每个类的定义中缺少db name的此属性:
__table_args__ = {'schema': 'Accounts'}
__table_args__ = {'schema': 'Billing'}