Fixed #27164 -- Fixed an example of using routers in multiple databases docs.

Make sure that AuthRouter includes ContentType in the same database.
This commit is contained in:
Caio Ariede 2019-11-18 09:35:31 -03:00 committed by Mariusz Felisiak
parent 0284a26af9
commit 608e06023e
1 changed files with 19 additions and 12 deletions

View File

@ -301,44 +301,51 @@ databases::
} }
Now we'll need to handle routing. First we want a router that knows to Now we'll need to handle routing. First we want a router that knows to
send queries for the ``auth`` app to ``auth_db``:: send queries for the ``auth`` and ``contenttypes`` apps to ``auth_db``
(``auth`` models are linked to ``ContentType``, so they must be stored in the
same database)::
class AuthRouter: class AuthRouter:
""" """
A router to control all database operations on models in the A router to control all database operations on models in the
auth application. auth and contenttypes applications.
""" """
route_app_labels = {'auth', 'contenttypes'}
def db_for_read(self, model, **hints): def db_for_read(self, model, **hints):
""" """
Attempts to read auth models go to auth_db. Attempts to read auth and contenttypes models go to auth_db.
""" """
if model._meta.app_label == 'auth': if model._meta.app_label in self.route_app_labels:
return 'auth_db' return 'auth_db'
return None return None
def db_for_write(self, model, **hints): def db_for_write(self, model, **hints):
""" """
Attempts to write auth models go to auth_db. Attempts to write auth and contenttypes models go to auth_db.
""" """
if model._meta.app_label == 'auth': if model._meta.app_label in self.route_app_labels:
return 'auth_db' return 'auth_db'
return None return None
def allow_relation(self, obj1, obj2, **hints): def allow_relation(self, obj1, obj2, **hints):
""" """
Allow relations if a model in the auth app is involved. Allow relations if a model in the auth or contenttypes apps is
involved.
""" """
if obj1._meta.app_label == 'auth' or \ if (
obj2._meta.app_label == 'auth': obj1._meta.app_label in self.route_app_labels or
obj2._meta.app_label in self.route_app_labels
):
return True return True
return None return None
def allow_migrate(self, db, app_label, model_name=None, **hints): def allow_migrate(self, db, app_label, model_name=None, **hints):
""" """
Make sure the auth app only appears in the 'auth_db' Make sure the auth and contenttypes apps only appear in the
database. 'auth_db' database.
""" """
if app_label == 'auth': if app_label in self.route_app_labels:
return db == 'auth_db' return db == 'auth_db'
return None return None