dynamically change db_alias

33 views
Skip to first unread message

JDDJ

unread,
Jan 26, 2012, 2:22:37 PM1/26/12
to MongoEngine Users
i am using dev version of mongoengine (0.5.3), and want to know if its
possible to change a document definition db_alias dynamically.

Ankhbayar Lhagvadorj

unread,
Feb 1, 2012, 11:35:33 PM2/1/12
to mongoeng...@googlegroups.com
Hello. 

It won't work using standard method. 

Use this method. This is little bit hard code. :(  

import mongoengine
import os
DEFAULT_DB = "default_db"

class DynamicAliasModel(mongoengine.Document):
    # .... model definition.
    @classmethod
    def _get_db(cls):
        dynamic_alias = os.environ.get("db_alias", DEFAULT_DB )
        return mongoengine.connection.get_db(dynamic_alias)


if you need to change variable os.environ["db_alias"]  you should delete cached collection instance.

from mongoengine import base
# Too Danger :( May be slow some code.
for key, doc_class in base._document_registry.items():
   doc_class._collection = None # Remove cache collection  
  


On Fri, Jan 27, 2012 at 3:22 AM, JDDJ <jaidee...@gmail.com> wrote:
i am using dev version of mongoengine (0.5.3), and want to know if its
possible to change a document definition db_alias dynamically.



--
Хүндэтгэсэн Анхбаяр

Ross Lawley

unread,
Feb 2, 2012, 5:07:23 AM2/2/12
to mongoeng...@googlegroups.com
Hi,

I havent looked into this but do you really have to change the cached _collection to None?

Also, to help me understand this what are your use cases for changing the db?

Ross
Reply all
Reply to author
Forward
0 new messages