Manager for multiple database connections


/ Published in: Python
Save to your folder(s)

A Django model manager capable of using different database connections.

Inspired by:

* [Eric Florenzano](http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/)
* [Kenneth Falck](http://kfalck.net/2009/07/01/multiple-databases-and-sharding-with-django)

There's a more detailed version in Portuguese in my blog:
[Manager para diferentes conexões de banco no Django](http://ricobl.wordpress.com/2009/08/06/manager-para-diferentes-conexoes-de-banco-no-django/)


Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.