Created
June 6, 2012 21:49
-
-
Save douglasmiranda/2885050 to your computer and use it in GitHub Desktop.
Django: Escolher db dinamicamente
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Resposta que surgiu nesta discussão: https://groups.google.com/forum/#!topic/django-brasil/3ADhmbltSUU | |
Então guardei aqui p/ testar em breve. | |
""" | |
Model.objects.using(Model.user_db(user)).all() ou | |
instance.save(using=Model.user_db(user)) | |
@classmethod | |
def user_db(cls, user): | |
try: | |
config = DBConfig.objects.get(user=user) | |
alias = '_'.join([user.username, config.db_name]) | |
if not alias in connections.databases: | |
db = connections.databases['default'].copy() | |
db['NAME'] = config.db_name | |
db['USER'] = config.db_user | |
db['PASSWORD'] = config.db_password | |
db['HOST'] = config.db_host | |
db['PORT'] = config.db_port or '' | |
connections.databases[alias] = db | |
except DBConfig.DoesNotExist: | |
alias = 'default' | |
return alias |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment