Return to Snippet

Revision: 16516
at August 6, 2009 20:42 by rix


Initial Code
# -*- coding: utf-8 -*-

"""
Sample settings:

DATABASE_ENGINE = 'postgresql_psycopg2'
DATABASE_NAME = 'default_db_name'
DATABASE_USER = 'user'
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''

# Any omitted property will inherit the default value from settings
DATABASES = {
    'default': {},
    'alternative': {
        'DATABASE_NAME': 'alternative_db_name',
    },
}
"""

from django.conf import settings
from django.db import models, backend

# Default connection
db_settings = {
    'DATABASE_HOST': settings.DATABASE_HOST,
    'DATABASE_NAME': settings.DATABASE_NAME,
    'DATABASE_OPTIONS': settings.DATABASE_OPTIONS,
    'DATABASE_PASSWORD': settings.DATABASE_PASSWORD,
    'DATABASE_PORT': settings.DATABASE_PORT,
    'DATABASE_USER': settings.DATABASE_USER,
    'TIME_ZONE': settings.TIME_ZONE,
}

def prepare_db_settings(db_profile_name):
    """
    Takes custom database settings, replaces missing values with the
    defaults from settings and returns a new connection dict.
    """
    return dict(db_settings, **settings.DATABASES[db_profile_name])

class MultiDBManager(models.Manager):
    """
    A manager that can connect to different databases.
    """
    def use(self, db_profile_name):
    	"""
    	Return a queryset connected to a custom database.
    	"""
        # Get customized database settings to use in a new connection wrapper
        db_settings = prepare_db_settings(db_profile_name)

    	# Get the queryset and replace its connection
        qs = self.get_query_set()
        qs.query.connection = backend.DatabaseWrapper(db_settings)
        return qs

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

Initial Description
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/)

Initial Title
Manager for multiple database connections

Initial Tags
database

Initial Language
Python