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博客 ” ,链接:https://blog.itpub.net/301743/viewspace-733300/
,如需转载,请注明出处,否则将追究法律责任。