Over a million developers have joined DZone.

Django: Switching Databases on Per-View Level

· Web Dev Zone

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

Django has a "multiple databases" feature that lets you read/write data from more than just the default database. I'm going to show you how to switch databases on a per-view level, rather than per-query with objects.using(), or per-server by changing DATABASE_ROUTERS.

First, some background. Let's look at how regular database routing works. It all starts with DATABASES in settings.py.

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myapp',
        'USER': 'postgres',
        'PASSWORD': 'password',
    'standby': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myapp',
        'USER': 'postgres',
        'PASSWORD': 'password',

 Then, you configure a database router. Here is an example that reads from one database and writes to another. Maybe standby is a read-replica of default.

class StandbyRouter(object):
    """A router to control all database operations on models in
    the website application"""

    def db_for_read(self, model, **hints):
        return "standby"

    def db_for_write(self, model, **hints):
        return "default"

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_syncdb(self, db, model):
        return None

 That's fine if you want ALL reads to go to the standby, but what if you only want to do this for some queries? In my situation, I wanted to off load long running queries specifically for reporting. Here is the standard syntax for querying from another server, assuming your router db_for_read() returns "default".

class UserProfile(models.Model):

    user = models.OneToOneField(User, editable=False, unique=True)

    def timecards(self):
        return Timecard.objects.filter(user=self.user, status='open')

def get_report_data(request):
    num_invoices = Invoices.objects.using("standby").filter(user=request.user).count()
    num_timecards = request.user.profile.timecards.count()

Maybe you see the problem here already. The using method is fine as long as you're making the queries yourself at the top level inside get_report_data(). But what about the timecards model property? It will use the default database. Sure, I could repeat myself all over the place passing around a parameter for the current database, and having a using clause on every single query, but that sounds messy.

Ideally, I want to set the database for an entire view at a time. Here's one way to do it. First, I declare a new router that dynamically chooses a database based on a setting.

class SettingsRouter(object):
    """A router to control all database operations on models in
    the website application. Can be over-ridden on demand with a
    decorator on a view or a particular function:

    def social_network_reach(request):

    This is more DRY than having a .using() on every query. It also
    means you don't have to pass a using parameter all over the place.


    def db_for_read(self, model, **hints):
        return get_thread_local('DB_FOR_READ_OVERRIDE', 'default')

    def db_for_write(self, model, **hints):
        return "default"

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_syncdb(self, db, model):
        return None

 To pass the DB_FOR_READ_OVERRIDE variable down the stack with out manually passing it via method arguments, I'm setting a thread local variable. This means that in a production setting, the variable will only be set in the context of the currently running request. Here is the decorator that does just that.

import threading
from functools import wraps

threadlocal = threading.local()

class thread_local(object):
    """ a decorator that wraps a function in a thread local definition block
    useful for passing variables down the stack w/o actually passing them
    examples: what database to read from, whether to cache queries, etc
    adapted from django.test.utils.override_settings


    def override(request):


    def __init__(self, **kwargs):
        self.options = kwargs

    def __enter__(self):
        for attr, value in self.options.items():
            print attr, value
            setattr(threadlocal, attr, value)

    def __exit__(self, exc_type, exc_value, traceback):
        for attr in self.options.keys():
            setattr(threadlocal, attr, None)

    def __call__(self, test_func):

        def inner(*args, **kwargs):
            # the thread_local class is also a context manager
            # which means it will call __enter__ and __exit__
            with self:
                return test_func(*args, **kwargs)

        return inner

def get_thread_local(attr, default=None):
    """ use this method from lower in the stack to get the value """
    return getattr(threadlocal, attr, default)

Finally, here is the what it looks like to use the new thread local variable to scope all of the inner queries to the standby database.

def get_report_data(request):
    num_invoices = Invoices.objects.filter(user=request.user).count()
    num_timecards = request.user.profile.timecards.count()


 Edit: I originally implemented this with @override_settings, before realizing that it would not work in a threaded production environment.

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.


Published at DZone with permission of Chase Seibert, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}