Many-to-many multi-database join with Flask-SQLAlchemy

2024/11/17 2:53:18

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!

Answer

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!

https://en.xdnf.cn/q/71269.html

Related Q&A

Merge two rows in the same Dataframe if their index is the same?

I have created a large Dataframe by pulling data from an Azure database. The construction of the dataframe wasnt simple as I had to do it in parts, using the concat function to add new columns to the d…

How do I use the Postgresql ANY operator in a NOT IN statement

Using Pyscopg2, how do I pass a Python list into an SQL statement using the ANY Operator?Normal Working SQL reads (See SQL Fiddle):SELECT * FROM student WHERE id NOT IN (3);Using Psycopg2 as below:Psy…

pass command-line arguments to runpy

I have two files, one which has a side effect I care about that occurs within the if __name__ == "__main__" guard:# a.py d = {} if __name__ == "__main__":d[arg] = helloThe second fi…

Altering my python path: helloworld.py returns command not found—

Massive apologies for this embarrassing question—Im using my MacBook Pro, running snow leopard, and using Python 2.7.1. Trying to run my first script and all the first pages of all my tutorials are la…

ImportError: cannot import name force_text

I have installed Python 2.7 and Django 1.4 in my CentOS machine and installed all dependencies for my existing project. When I run python manage.py runserver, I am getting the following traceback in my…

How can I select the pixels that fall within a contour in an image represented by a numpy array?

VI have a set of contour points drawn on an image which is stored as a 2D numpy array. The contours are represented by 2 numpy arrays of float values for x and y coordinates each. These coordinates are…

Get the value of specific JSON element in Python

Im new to Python and JSON, so Im sorry if I sound clueless. Im getting the following result from the Google Translate API and want to parse out the value of "translatedText":{"data"…

How does setuptools decide which files to keep for sdist/bdist?

Im working on a Python package that uses namespace_packages and find_packages() like so in setup.py:from setuptools import setup, find_packages setup(name="package",version="1.3.3.7"…

How to implement multivariate linear stochastic gradient descent algorithm in tensorflow?

I started with simple implementation of single variable linear gradient descent but dont know to extend it to multivariate stochastic gradient descent algorithm ?Single variable linear regression impo…

How to do os.execv() in Python in Windows without detaching from the console?

Im using Python 2.6 on Windows 7. I have Windows .cmd file which invokes Python to run the CherryPy Web server (version 3.1.2). I start this .cmd file by executing it at the prompt in a Windows CMD she…