Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Here's the basics...

I've got main_db and vendor_db. The tables are setup as main_db.users, main_db.user_products (the relation table), and then 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.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. Any ideas how I can make it use main_db instead? 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. Thanks!

like image 862
jeffff Avatar asked Jul 11 '12 17:07

jeffff


People also ask

How do you create a many to many relationship in SQLAlchemy?

You add a tags class variable to the Post model. You use the db. relationship() method, passing it the name of the tags model ( Tag in this case). You pass the post_tag association table to the secondary parameter to establish a many-to-many relationship between posts and tags.

How can you perform many to many relationship in Python?

Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.


1 Answers

Turns out what I needed to do here was specify the schema in my user_products_tbl table definition. 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!

like image 178
jeffff Avatar answered Sep 21 '22 19:09

jeffff