mirror of https://github.com/django/django.git
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:
parent
0284a26af9
commit
608e06023e
|
@ -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
|
||||
|
||||
|
|
Loading…
Reference in New Issue