Recently, we need to use Django 's MySQL Read-write separation technology, looked up some information, the method was sorted down.
In the Django Implementation of the MySQL Read and write separation, in fact, the different read and write requests according to certain rules to the different database (can be different types of database), we need to do is, Define different databases and define different routing rules.
First define our master-slave database:
DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ',
' NAME ': Sae.const.MYSQL_DB,
' USER ': Sae.const.MYSQL_USER,
' PASSWORD ': Sae.const.MYSQL_PASS,
' HOST ': Sae.const.MYSQL_HOST,
' PORT ': Sae.const.MYSQL_PORT,
},
' slave ': {
' ENGINE ': ' Django.db.backends.mysql ',
' NAME ': Sae.const.MYSQL_DB,
' USER ': Sae.const.MYSQL_USER,
' PASSWORD ': Sae.const.MYSQL_PASS,
' HOST ': Sae.const.MYSQL_HOST_S,
' PORT ': Sae.const.MYSQL_PORT,
},
}
Define our routing rules, there can be multiple routing rules, and each rule is a class. As shown below:
#-*-Coding:utf-8-*-
Class Dbrouter (object):
def db_for_read (self, model, **hints):
Return ' slave '
def db_for_write (self, model, **hints):
Return ' Default '
def allow_relation (self, obj1, Obj2, **hints):
Return None
def allow_syncdb (self, DB, model):
Return None
Finally, Add this routing rule to the setting.py:
Database_routers = [' Opensound.models.DBRouter ']
Because Django is not responsible for synchronization between master and slave databases, if you want to manipulate the data immediately after reading the data, you can explicitly use the primary database to read and modify the data.
>>> Author.objects.using (' other '). All ()
>>> my_object.save (using= ' legacy_users ')
Reference: https://docs.djangoproject.com/en/dev/topics/db/multi-db/
Http://www.truease.com/thread-262-1-1.html
MySQL read-write separation technology in Django