Separate read and write
The basic principle is to make the main transactional database processing add, change, delete operations (INSERT, UPDATE, DELETE) operation, while processing SELECT queries from the database, the database is used to copy things change operations resulting from other databases to synchronize to SQL, for example, the master database is responsible for writing data, reading data, read only responsible for reading data library, the library every write operation, synchronous update the library to read, to write a library, reading library can have multiple, synchronized using logs master database for data and synchronization of multiple databases
Specific configuration is as follows
Increase the allocation slave database in the configuration file
In the configuration file settings.py Django, DATABASES add the following code:
= {DATABASES 'default': { 'ENGINE': 'django.db.backends.mysql', 'the HOST': '127.0.0.1', run # master server IP 'PORT': 3306, master server running port # 'uSER': 'django', username # primary server 'pASSWORD': 'django', password # master server 'nAME': 'djangobase' # table name }, 'Slave': { 'ENGINE': ' django.db.backends.mysql ', ' the HOST ':' 127.0.0.1 ', ' PORT ': 8306, ' the USER ':' django_slave ', ' PASSWORD ':' django_slave ', ' NAME ':'djangobase_slave' } }
Create a route classification database operations
Create db_router.py utils project files, and the definition of a class in the file db, used for separate read and write
MasterSlaveDBRouter class (Object): "" "separate route from the master database to read and write" "" DEF db_for_read (Self, Model, hints **): "" "Read Database" "" return "Slave" DEF db_for_write (Self, Model, hints **): "" "database write" "" return "default" DEF allow_relation (Self, obj1, obj2, hints **): "" "associated with the operation is running" "" return True
Configuring route separate read and write
Increase in the configuration file
# Set the separate read and write DATABASE_ROUTERS = [ 'item name .utils.db_router. "Custom class name' ']