Posted By

rix on 08/06/09


Tagged

database connection databases manager multiple connections


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

rix


Manager for multiple database connections


 / Published in: Python
 

URL: http://ricobl.wordpress.com/2009/08/06/manager-para-diferentes-conexoes-de-banco-no-django/

A Django model manager capable of using different database connections.

Inspired by:

There's a more detailed version in Portuguese in my blog: Manager para diferentes conexões de banco no Django

  1. # -*- coding: utf-8 -*-
  2.  
  3. """
  4. Sample settings:
  5.  
  6. DATABASE_ENGINE = 'postgresql_psycopg2'
  7. DATABASE_NAME = 'default_db_name'
  8. DATABASE_USER = 'user'
  9. DATABASE_PASSWORD = ''
  10. DATABASE_HOST = ''
  11. DATABASE_PORT = ''
  12.  
  13. # Any omitted property will inherit the default value from settings
  14. DATABASES = {
  15. 'default': {},
  16. 'alternative': {
  17. 'DATABASE_NAME': 'alternative_db_name',
  18. },
  19. }
  20. """
  21.  
  22. from django.conf import settings
  23. from django.db import models, backend
  24.  
  25. # Default connection
  26. db_settings = {
  27. 'DATABASE_HOST': settings.DATABASE_HOST,
  28. 'DATABASE_NAME': settings.DATABASE_NAME,
  29. 'DATABASE_OPTIONS': settings.DATABASE_OPTIONS,
  30. 'DATABASE_PASSWORD': settings.DATABASE_PASSWORD,
  31. 'DATABASE_PORT': settings.DATABASE_PORT,
  32. 'DATABASE_USER': settings.DATABASE_USER,
  33. 'TIME_ZONE': settings.TIME_ZONE,
  34. }
  35.  
  36. def prepare_db_settings(db_profile_name):
  37. """
  38. Takes custom database settings, replaces missing values with the
  39. defaults from settings and returns a new connection dict.
  40. """
  41. return dict(db_settings, **settings.DATABASES[db_profile_name])
  42.  
  43. class MultiDBManager(models.Manager):
  44. """
  45. A manager that can connect to different databases.
  46. """
  47. def use(self, db_profile_name):
  48. """
  49. Return a queryset connected to a custom database.
  50. """
  51. # Get customized database settings to use in a new connection wrapper
  52. db_settings = prepare_db_settings(db_profile_name)
  53.  
  54. # Get the queryset and replace its connection
  55. qs = self.get_query_set()
  56. qs.query.connection = backend.DatabaseWrapper(db_settings)
  57. return qs

Report this snippet  

You need to login to post a comment.