How do I implement database routing in Django? __ Database

Source: Internet
Author: User

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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.