ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Django Switching Databases on Per-View Level

Django Switching Databases on Per-View Level

原创 Linux操作系统 作者:jieforest 时间:2012-06-20 10:16:22 0 删除 编辑
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/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-04-23

  • 博文量
    443
  • 访问量
    508038