Connecting to multiple mongodb instances from django

谁都会走 提交于 2019-12-01 22:19:19

问题


I am using mongoengine with Django and within my project need to connect to two instances of MongoDB while serving single request. It works just fine if I use:

connect("mdb1")
#do stuff with mdb1
...
connect("mdb2")
#do stuff with mdb2

but I am wondering if that's a proper way of doing it.


回答1:


Multiple database support was added in MongoEngine 0.6

Demo using register_connection.

alias_lists = ['users-books-db', 'user-db', 'book-db'] # list of aliases
dbs = ['author-book-pairs', 'users', 'books'] # list of databases
for alias, db in zip(alias_lists, dbs):
    register_connection(alias, db)

class User(Document):
    name = StringField()
    meta = {"db_alias": "user-db"}

class Book(Document):
    name = StringField()
    meta = {"db_alias": "book-db"}

class AuthorBooks(Document):
    author = ReferenceField(User)
    book = ReferenceField(Book)
    meta = {"db_alias": "users-books-db"}



回答2:


@Ricardo at the official documentation theres a section explaining context management (i.e switching databases using the same document: http://mongoengine-odm.readthedocs.org/en/latest/guide/connecting.html#context-managers). The following code will switch the class User, originally stored in users-db to the new database archive-user-db

from mongoengine.context_managers import switch_db

class User(Document):
     name = StringField()

     meta = {"db_alias": "user-db"}

with switch_db(User, 'archive-user-db') as User:
     User(name="Ross").save()  # Saves the 'archive-user-db'



回答3:


I think there is no a proper way to do this. The example of Matt turns obligatory use an connection by Document type. If I want to use one document with many connections the example doesn't fit.



来源:https://stackoverflow.com/questions/6067645/connecting-to-multiple-mongodb-instances-from-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!