2013-05-15 48 views
5

我試圖做一個跨數據庫加入燒瓶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 for'object does not exist')失敗。

如果我檢查生成的SQL,我可以清楚地看到它正在對Account.AccountId = Accounts.id進行JOIN,當我期望看到對帳單的某些引用時(例如, Billing.Account.AccountId = Accounts.id。

跟着Cross database join in sqlalchemyhttp://pythonhosted.org/Flask-SQLAlchemy/binds.html它看起來好像我做了正確的事情。是什麼賦予了?

回答

1

您定義了一個對象db = SQLAlchemy(app) - 它是Database1。您在任何地方都可以參考它,但是沒有提及Database2。另外要注意的代碼是指列的連接使用2個部分標識符:而你希望有3個部分標識符

Account . AccountId and Accounts . id 

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

您從每個類別的定義缺少此屬性數據庫名稱:

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