Skip to content

Commit

Permalink
[2.2.x] Fixed #27164 -- Fixed an example of using routers in multiple…
Browse files Browse the repository at this point in the history
… databases docs.

Make sure that AuthRouter includes ContentType in the same database.

Backport of 608e060 from master
  • Loading branch information
caioariede authored and felixxm committed Nov 20, 2019
1 parent 4082f07 commit 11e4200
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions docs/topics/db/multi-db.txt
Original file line number Diff line number Diff line change
Expand Up @@ -301,44 +301,51 @@ databases::
}

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:
"""
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):
"""
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 None

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 None

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 \
obj2._meta.app_label == 'auth':
if (
obj1._meta.app_label in self.route_app_labels or
obj2._meta.app_label in self.route_app_labels
):
return True
return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
Make sure the auth and contenttypes apps only appear in the
'auth_db' database.
"""
if app_label == 'auth':
if app_label in self.route_app_labels:
return db == 'auth_db'
return None

Expand Down

0 comments on commit 11e4200

Please sign in to comment.