Django Switching Databases on Per-View Level

jieforest發表於2012-06-20
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.

CODE:

DATABASES = {
    '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.

CODE:

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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-733300/,如需轉載,請註明出處,否則將追究法律責任。

相關文章