I have Flask app with a Post
model which spans across multiple MongoDB databases (db1, db2, db3,...), so I need to be able to query different dbs.
I'm using Flask-MongoEngine
extension.
My __init__.py
contains the following line:
db = MongoEngine(app)
and in config.py
I have:
MONGODB_SETTINGS = {'DB': 'db1'}
I tried the following without success:
- Alter the
connection
parameter in thedb
object like this:
db.connection = mongoengine.connect('db2')
It didn't change anything. Executingpost = Post.objects.all()
still ran on the original db (db1
). - Create alias in the
Post
classmeta
like this:
'db_alias': 'db1'
Then I altered theconnection
parameter in thedb
object like this:
db.connection = mongoengine.connect('db2', alias='db1')
This would indeed create a connection todb2
, but I couldn't change it to another db. - Set
MONGODB_SETTINGS
to{'DB': 'db2'}
and thendb = MongoEngine(app)
This doesn't work as well
It seems like once the model in models.py
has been loaded (or connected to a db), you cannot change its connection.
Is that correct?
How can I change databases on the same model?
EDIT: The Django equivalent is the using
parameter in the ORM which allows querying different DBs for the same model.