简体   繁体   English

使用Flask-SQLAlchemy进行多对多多数据库连接

[英]Many-to-many multi-database join with Flask-SQLAlchemy

I'm trying to make this many-to-many join work with Flask-SQLAlchemy and two MySQL databases, and it's very close except it's using the wrong database for the join table. 我正在尝试使用Flask-SQLAlchemy和两个MySQL数据库进行多对多连接,除非它使用错误的数据库连接表,否则它非常接近。 Here's the basics... 这是基础......

I've got main_db and vendor_db . 我有main_dbvendor_db The tables are setup as main_db.users , main_db.user_products (the relation table), and then vendor_db.products . 这些表设置为main_db.usersmain_db.user_products (关系表),然后是vendor_db.products Should be pretty clear how those are all connected. 应该很清楚这些是如何连接的。

in my app.py, I'm seting up the databases like this: 在我的app.py中,我正在设置这样的数据库:

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:pass@localhost/main_db'
app.config['SQLALCHEMY_BINDS'] = {
        'vendor_db': 'mysql://user:pass@localhost/vendor_db'
}

Model definitions are set up like this: 模型定义设置如下:

from app import db

# Setup relationship
user_products_tbl = db.Table('user_products', db.metadata,
        db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')),
        db.Column('product_id', db.Integer, db.ForeignKey('products.product_id'))
)

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column('user_id', db.Integer, primary_key=True)
    products = db.relationship("Product", secondary=user_products_tbl,
            backref="users", lazy="dynamic")

class Product(db.Model):
    __bind_key__ = 'vendor_db'
    __tablename__ = 'products'
    id = db.Column('product_id', db.Integer, primary_key=True)
    name = db.Column(db.String(120))

The problem is that when I try to get a user's products it's trying to use vendor_db for the join table instead of main_db . 问题是,当我尝试获取用户的产品时,它试图使用vendor_db作为连接表而不是main_db Any ideas how I can make it use main_db instead? 有什么想法我可以使用main_db吗? I've tried setting up another bind to main_db and setting info={'bind_key': 'main_db'} on the relationship table definition, but no luck. 我已经尝试设置另一个绑定到main_db并在关系表定义上设置info={'bind_key': 'main_db'} ,但没有运气。 Thanks! 谢谢!

Turns out what I needed to do here was specify the schema in my user_products_tbl table definition. 原来我需要做的是在user_products_tbl表定义中指定模式。 So, 所以,

user_products_tbl = db.Table('user_products', db.metadata,
        db.Column('user_id', db.Integer, db.ForeignKey('users.user_id')),
        db.Column('product_id', db.Integer, db.ForeignKey('products.product_id')),
        schema='main_db'
)

Hope this helps someone else! 希望这有助于其他人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM