Connecting to multiple mongodb instances from django

前端 未结 3 1602
慢半拍i
慢半拍i 2021-01-20 23:23

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:

c         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 00:21

    @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'
    

提交回复
热议问题