join - 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'
    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 sqlalchemyhttp://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/

相关文章:

javascript - 大量提供用户定制的脚本

python-3.x - Flask - 防止函数重新加载?

mysql - 需要连接 2 个表,但 MySQL 中另一个表中的某些行除外

php - 如何在 JOIN 中包含附加的 select 语句? PHP-MySQL

mysql - 我如何构建这个 JOIN 语句?遇到条件困难

python - 如何调用 python/flask 服务器从服务器端功能重新加载客户端页面?

MySQL - 查询 MySQL 中的大表 -

python - scrapy 数据库插入失败但没有错误

python - 如何在 SQLAlchemy 的原始 JOIN 查询中正确选择重复的字段名称

python - 将 Pandas 数据框上传到 MySQL 数据库后如何获取列的自动增量值