Although we provide information about the database, it knows how to connect to the database, but the problem is that we have a lot of models in it, and it doesn't know which model to store in which database. This requires us to specify, that is, ourselves to implement a database route. A database route is a class that has 4 methods, and these four methods are:
Db_for_read (model, **hints)
Which database to use for this model to read.
Db_for_write (model, **hints)
Write to which database the model is written in.
Allow_relation (Obj1, Obj2, **hints)
Whether two objects are allowed to be associated with the database.
Allow_migrate (db, App_label, Model_name=none, **hints)
For the specified app, is the DB this database allowed to be migrate
Open the routers.py file and make the following configuration:
Class Sampledbrouter (object):
def db_for_read (self, model, **hints):
if Model._meta.label = = ' Multidb.logger ':
Return ' logs ' (if it is Logger's model), returns the logs database. Save information to LAB2)
elif Model._meta.label = = ' Multidb.loguser ':
Return the ' users ' (if it is LogUser's model) and go back to the users database. Save information to LAB1)
Return None
def db_for_write (self, model, **hints):
if Model._meta.label = = ' Multidb.logger ':
Return ' logs '
elif Model._meta.label = = ' Multidb.loguser ':
Return ' users '
Return None
def allow_relation (self, obj1, Obj2, **hints):
Return True (association, stored to the specified place). )
def allow_migrate (self, DB, App_label, Model=none, **hints):
if Model._meta.label = = ' Multidb.logger ':
return db = = ' Logs ' (if the model is MULTIDB.) Logger, the database is logs, you can migrate.
elif Model._meta.label = = ' Multidb.loguser ':
return db = = ' users ' if the model is MULTIDB. LogUser, the database is users, you can migrate)
Return None
Original link: http://www.maiziedu.com/wiki/django/server/