Code documentation

dynamic_db_router

class dynamic_db_router.in_database(database, read=True, write=False)

A decorator and context manager to do queries on a given database.

Parameters:
  • database (str or dict) – The database to run queries on. A string will route through the matching database in django.conf.settings.DATABASES. A dictionary will set up a connection with the given configuration and route queries to it.
  • read (bool, optional) – Controls whether database reads will route through the provided database. If False, reads will route through the 'default' database. Defaults to True.
  • write (bool, optional) – Controls whether database writes will route to the provided database. If False, writes will route to the 'default' database. Defaults to False.

When used as eithe a decorator or a context manager, in_database requires a single argument, which is the name of the database to route queries to, or a configuration dictionary for a database to route to.

Usage as a context manager:

from my_django_app.utils import tricky_query

with in_database('Database_A'):
    results = tricky_query()

Usage as a decorator:

from my_django_app.models import Account

@in_database('Database_B')
def lowest_id_account():
    Account.objects.order_by('-id')[0]

Used with a configuration dictionary:

db_config = {'ENGINE': 'django.db.backends.sqlite3',
             'NAME': 'path/to/mydatabase.db'}
with in_database(db_config):
    # Run queries