lew*_*wiz 6 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
Run Code Online (Sandbox Code Playgroud)
有了这个,我可以成功查询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数据库加入后,它看起来好像我已经做好了事情.是什么赋予了?
您定义一个对象db = SQLAlchemy(app)- 它是 Database1。您到处都引用它,但没有引用 Database2。另请注意,代码引用使用 2 部分标识符的联接的列:
Account . AccountId and Accounts . id
Run Code Online (Sandbox Code Playgroud)
而您希望有 3 个部分标识符:
Billing . Account . AccountId and [Accounts] . Accounts . id
Run Code Online (Sandbox Code Playgroud)
您在每个类的定义中缺少数据库名称的此属性:
__table_args__ = {'schema': 'Accounts'}
__table_args__ = {'schema': 'Billing'}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1284 次 |
| 最近记录: |