Create a database:
= DATABASES { ' default ' : { ' ENGINE ' : ' django.db.backends.mysql ' , ' NAME ' : ' default ' , ' the HOST ' : ' 127.0.0.1 ' , # operation of the main server IP ' PORT ' : 3306, # run the port master of ' the uSER ' : ' root ' , # user name of the primary server 'PASSWORD' : ' 123456 ' , # password master server }, ' Slave ' : { ' ENGINE ' : ' django.db.backends.mysql ' , ' NAME ' : ' Slave ' , ' the HOST ' : ' 127.0.0.1 ' , ' PORT ' : 3306 , ' the USER ' : ' the root ', 'PASSWORD': '123456', } }
Models built table:
from django.db Import Models # the Create your Models here Wallpaper. class Article This article was (models.Model): # verbose_name Chinese display of the field in the admin title = models.CharField (64-max_length = ) # Abstract desc = models.CharField (max_length = 255)
Database Migration:
manage.py makemigrations Python # In migrations folder generated record Python manage.py the migrate --database default # default parameters can not write Python manage.py the migrate --database Slave # migrate from the library once, you can build on it same table
Created in the app project db_router.py file and define a routing database class in the file for read and write separation, this class provides a maximum of four methods, namely: db_for_read
, , db_for_write
, allow_relation
, allow_migrate
just write the following three .
class MasterSlaveDBRouter (Object): "" " database from the master routing isolated read " "" DEF db_for_read (Self, Model, ** hints): "" " Read Database " "" return " Slave " DEF db_for_write (Self, Model, ** hints): "" " write database " "" return " default " DEF allow_relation (Self, obj1, obj2, ** hints): "" " whether to run the association operation " "" return True
Note configured in settings.py in:
DATABASE_ROUTERS = ["app001.db_router.MasterSlaveDBRouter"]
View function can operate:
DEF the Write (Request):
models.Article.objects.create (title = ' Dream of Red Mansions ' , desc = ' Good ' )
# using a using ( 'default') may specify the database
return HttpResponse ( ' Write Success ' )
DEF the Read (Request) :
obj = models.Article.objects.filter (title = ' Journey ' ) .first ()
Print (obj.title)
return the HttpResponse ( " read successful " )