1. ==================
    
  2. Multiple databases
    
  3. ==================
    
  4. 
    
  5. This topic guide describes Django's support for interacting with
    
  6. multiple databases. Most of the rest of Django's documentation assumes
    
  7. you are interacting with a single database. If you want to interact
    
  8. with multiple databases, you'll need to take some additional steps.
    
  9. 
    
  10. .. seealso::
    
  11. 
    
  12.     See :ref:`testing-multi-db` for information about testing with multiple
    
  13.     databases.
    
  14. 
    
  15. Defining your databases
    
  16. =======================
    
  17. 
    
  18. The first step to using more than one database with Django is to tell
    
  19. Django about the database servers you'll be using. This is done using
    
  20. the :setting:`DATABASES` setting. This setting maps database aliases,
    
  21. which are a way to refer to a specific database throughout Django, to
    
  22. a dictionary of settings for that specific connection. The settings in
    
  23. the inner dictionaries are described fully in the :setting:`DATABASES`
    
  24. documentation.
    
  25. 
    
  26. Databases can have any alias you choose. However, the alias
    
  27. ``default`` has special significance. Django uses the database with
    
  28. the alias of ``default`` when no other database has been selected.
    
  29. 
    
  30. The following is an example ``settings.py`` snippet defining two
    
  31. databases -- a default PostgreSQL database and a MySQL database called
    
  32. ``users``::
    
  33. 
    
  34.     DATABASES = {
    
  35.         'default': {
    
  36.             'NAME': 'app_data',
    
  37.             'ENGINE': 'django.db.backends.postgresql',
    
  38.             'USER': 'postgres_user',
    
  39.             'PASSWORD': 's3krit'
    
  40.         },
    
  41.         'users': {
    
  42.             'NAME': 'user_data',
    
  43.             'ENGINE': 'django.db.backends.mysql',
    
  44.             'USER': 'mysql_user',
    
  45.             'PASSWORD': 'priv4te'
    
  46.         }
    
  47.     }
    
  48. 
    
  49. If the concept of a ``default`` database doesn't make sense in the context
    
  50. of your project, you need to be careful to always specify the database
    
  51. that you want to use. Django requires that a ``default`` database entry
    
  52. be defined, but the parameters dictionary can be left blank if it will not be
    
  53. used. To do this, you must set up :setting:`DATABASE_ROUTERS` for all of your
    
  54. apps' models, including those in any contrib and third-party apps you're using,
    
  55. so that no queries are routed to the default database. The following is an
    
  56. example ``settings.py`` snippet defining two non-default databases, with the
    
  57. ``default`` entry intentionally left empty::
    
  58. 
    
  59.     DATABASES = {
    
  60.         'default': {},
    
  61.         'users': {
    
  62.             'NAME': 'user_data',
    
  63.             'ENGINE': 'django.db.backends.mysql',
    
  64.             'USER': 'mysql_user',
    
  65.             'PASSWORD': 'superS3cret'
    
  66.         },
    
  67.         'customers': {
    
  68.             'NAME': 'customer_data',
    
  69.             'ENGINE': 'django.db.backends.mysql',
    
  70.             'USER': 'mysql_cust',
    
  71.             'PASSWORD': 'veryPriv@ate'
    
  72.         }
    
  73.     }
    
  74. 
    
  75. If you attempt to access a database that you haven't defined in your
    
  76. :setting:`DATABASES` setting, Django will raise a
    
  77. ``django.utils.connection.ConnectionDoesNotExist`` exception.
    
  78. 
    
  79. .. _synchronizing_multiple_databases:
    
  80. 
    
  81. Synchronizing your databases
    
  82. ============================
    
  83. 
    
  84. The :djadmin:`migrate` management command operates on one database at a
    
  85. time. By default, it operates on the ``default`` database, but by
    
  86. providing the :option:`--database <migrate --database>` option, you can tell it
    
  87. to synchronize a different database. So, to synchronize all models onto
    
  88. all databases in the first example above, you would need to call::
    
  89. 
    
  90.     $ ./manage.py migrate
    
  91.     $ ./manage.py migrate --database=users
    
  92. 
    
  93. If you don't want every application to be synchronized onto a
    
  94. particular database, you can define a :ref:`database
    
  95. router<topics-db-multi-db-routing>` that implements a policy
    
  96. constraining the availability of particular models.
    
  97. 
    
  98. If, as in the second example above, you've left the ``default`` database empty,
    
  99. you must provide a database name each time you run :djadmin:`migrate`. Omitting
    
  100. the database name would raise an error. For the second example::
    
  101. 
    
  102.     $ ./manage.py migrate --database=users
    
  103.     $ ./manage.py migrate --database=customers
    
  104. 
    
  105. Using other management commands
    
  106. -------------------------------
    
  107. 
    
  108. Most other ``django-admin`` commands that interact with the database operate in
    
  109. the same way as :djadmin:`migrate` -- they only ever operate on one database at
    
  110. a time, using ``--database`` to control the database used.
    
  111. 
    
  112. An exception to this rule is the :djadmin:`makemigrations` command. It
    
  113. validates the migration history in the databases to catch problems with the
    
  114. existing migration files (which could be caused by editing them) before
    
  115. creating new migrations. By default, it checks only the ``default`` database,
    
  116. but it consults the :meth:`allow_migrate` method of :ref:`routers
    
  117. <topics-db-multi-db-routing>` if any are installed.
    
  118. 
    
  119. .. _topics-db-multi-db-routing:
    
  120. 
    
  121. Automatic database routing
    
  122. ==========================
    
  123. 
    
  124. The easiest way to use multiple databases is to set up a database
    
  125. routing scheme. The default routing scheme ensures that objects remain
    
  126. 'sticky' to their original database (i.e., an object retrieved from
    
  127. the ``foo`` database will be saved on the same database). The default
    
  128. routing scheme ensures that if a database isn't specified, all queries
    
  129. fall back to the ``default`` database.
    
  130. 
    
  131. You don't have to do anything to activate the default routing scheme
    
  132. -- it is provided 'out of the box' on every Django project. However,
    
  133. if you want to implement more interesting database allocation
    
  134. behaviors, you can define and install your own database routers.
    
  135. 
    
  136. Database routers
    
  137. ----------------
    
  138. 
    
  139. A database Router is a class that provides up to four methods:
    
  140. 
    
  141. .. method:: db_for_read(model, **hints)
    
  142. 
    
  143.     Suggest the database that should be used for read operations for
    
  144.     objects of type ``model``.
    
  145. 
    
  146.     If a database operation is able to provide any additional
    
  147.     information that might assist in selecting a database, it will be
    
  148.     provided in the ``hints`` dictionary. Details on valid hints are
    
  149.     provided :ref:`below <topics-db-multi-db-hints>`.
    
  150. 
    
  151.     Returns ``None`` if there is no suggestion.
    
  152. 
    
  153. .. method:: db_for_write(model, **hints)
    
  154. 
    
  155.     Suggest the database that should be used for writes of objects of
    
  156.     type Model.
    
  157. 
    
  158.     If a database operation is able to provide any additional
    
  159.     information that might assist in selecting a database, it will be
    
  160.     provided in the ``hints`` dictionary. Details on valid hints are
    
  161.     provided :ref:`below <topics-db-multi-db-hints>`.
    
  162. 
    
  163.     Returns ``None`` if there is no suggestion.
    
  164. 
    
  165. .. method:: allow_relation(obj1, obj2, **hints)
    
  166. 
    
  167.     Return ``True`` if a relation between ``obj1`` and ``obj2`` should be
    
  168.     allowed, ``False`` if the relation should be prevented, or ``None`` if
    
  169.     the router has no opinion. This is purely a validation operation,
    
  170.     used by foreign key and many to many operations to determine if a
    
  171.     relation should be allowed between two objects.
    
  172. 
    
  173.     If no router has an opinion (i.e. all routers return ``None``), only
    
  174.     relations within the same database are allowed.
    
  175. 
    
  176. .. method:: allow_migrate(db, app_label, model_name=None, **hints)
    
  177. 
    
  178.     Determine if the migration operation is allowed to run on the database with
    
  179.     alias ``db``. Return ``True`` if the operation should run, ``False`` if it
    
  180.     shouldn't run, or ``None`` if the router has no opinion.
    
  181. 
    
  182.     The ``app_label`` positional argument is the label of the application
    
  183.     being migrated.
    
  184. 
    
  185.     ``model_name`` is set by most migration operations to the value of
    
  186.     ``model._meta.model_name`` (the lowercased version of the model
    
  187.     ``__name__``) of the model being migrated. Its value is ``None`` for the
    
  188.     :class:`~django.db.migrations.operations.RunPython` and
    
  189.     :class:`~django.db.migrations.operations.RunSQL` operations unless they
    
  190.     provide it using hints.
    
  191. 
    
  192.     ``hints`` are used by certain operations to communicate additional
    
  193.     information to the router.
    
  194. 
    
  195.     When ``model_name`` is set, ``hints`` normally contains the model class
    
  196.     under the key ``'model'``. Note that it may be a :ref:`historical model
    
  197.     <historical-models>`, and thus not have any custom attributes, methods, or
    
  198.     managers. You should only rely on ``_meta``.
    
  199. 
    
  200.     This method can also be used to determine the availability of a model on a
    
  201.     given database.
    
  202. 
    
  203.     :djadmin:`makemigrations` always creates migrations for model changes, but
    
  204.     if ``allow_migrate()`` returns ``False``, any migration operations for the
    
  205.     ``model_name`` will be silently skipped when running :djadmin:`migrate` on
    
  206.     the ``db``. Changing the behavior of ``allow_migrate()`` for models that
    
  207.     already have migrations may result in broken foreign keys, extra tables,
    
  208.     or missing tables. When :djadmin:`makemigrations` verifies the migration
    
  209.     history, it skips databases where no app is allowed to migrate.
    
  210. 
    
  211. A router doesn't have to provide *all* these methods -- it may omit one
    
  212. or more of them. If one of the methods is omitted, Django will skip
    
  213. that router when performing the relevant check.
    
  214. 
    
  215. .. _topics-db-multi-db-hints:
    
  216. 
    
  217. Hints
    
  218. ~~~~~
    
  219. 
    
  220. The hints received by the database router can be used to decide which
    
  221. database should receive a given request.
    
  222. 
    
  223. At present, the only hint that will be provided is ``instance``, an
    
  224. object instance that is related to the read or write operation that is
    
  225. underway. This might be the instance that is being saved, or it might
    
  226. be an instance that is being added in a many-to-many relation. In some
    
  227. cases, no instance hint will be provided at all. The router checks for
    
  228. the existence of an instance hint, and determine if that hint should be
    
  229. used to alter routing behavior.
    
  230. 
    
  231. Using routers
    
  232. -------------
    
  233. 
    
  234. Database routers are installed using the :setting:`DATABASE_ROUTERS`
    
  235. setting. This setting defines a list of class names, each specifying a
    
  236. router that should be used by the base router
    
  237. (``django.db.router``).
    
  238. 
    
  239. The base router is used by Django's database operations to allocate
    
  240. database usage. Whenever a query needs to know which database to use,
    
  241. it calls the base router, providing a model and a hint (if
    
  242. available). The base router tries each router class in turn until one returns
    
  243. a database suggestion. If no routers return a suggestion, the base router tries
    
  244. the current :attr:`instance._state.db
    
  245. <django.db.models.Model._state>` of the hint instance. If no hint instance
    
  246. was provided, or :attr:`instance._state.db <django.db.models.Model._state>` is
    
  247. ``None``, the base router will allocate the ``default`` database.
    
  248. 
    
  249. An example
    
  250. ----------
    
  251. 
    
  252. .. admonition:: Example purposes only!
    
  253. 
    
  254.     This example is intended as a demonstration of how the router
    
  255.     infrastructure can be used to alter database usage. It
    
  256.     intentionally ignores some complex issues in order to
    
  257.     demonstrate how routers are used.
    
  258. 
    
  259.     This example won't work if any of the models in ``myapp`` contain
    
  260.     relationships to models outside of the ``other`` database.
    
  261.     :ref:`Cross-database relationships <no_cross_database_relations>`
    
  262.     introduce referential integrity problems that Django can't
    
  263.     currently handle.
    
  264. 
    
  265.     The primary/replica (referred to as master/slave by some databases)
    
  266.     configuration described is also flawed -- it
    
  267.     doesn't provide any solution for handling replication lag (i.e.,
    
  268.     query inconsistencies introduced because of the time taken for a
    
  269.     write to propagate to the replicas). It also doesn't consider the
    
  270.     interaction of transactions with the database utilization strategy.
    
  271. 
    
  272. So - what does this mean in practice? Let's consider another sample
    
  273. configuration. This one will have several databases: one for the
    
  274. ``auth`` application, and all other apps using a primary/replica setup
    
  275. with two read replicas. Here are the settings specifying these
    
  276. databases::
    
  277. 
    
  278.     DATABASES = {
    
  279.         'default': {},
    
  280.         'auth_db': {
    
  281.             'NAME': 'auth_db_name',
    
  282.             'ENGINE': 'django.db.backends.mysql',
    
  283.             'USER': 'mysql_user',
    
  284.             'PASSWORD': 'swordfish',
    
  285.         },
    
  286.         'primary': {
    
  287.             'NAME': 'primary_name',
    
  288.             'ENGINE': 'django.db.backends.mysql',
    
  289.             'USER': 'mysql_user',
    
  290.             'PASSWORD': 'spam',
    
  291.         },
    
  292.         'replica1': {
    
  293.             'NAME': 'replica1_name',
    
  294.             'ENGINE': 'django.db.backends.mysql',
    
  295.             'USER': 'mysql_user',
    
  296.             'PASSWORD': 'eggs',
    
  297.         },
    
  298.         'replica2': {
    
  299.             'NAME': 'replica2_name',
    
  300.             'ENGINE': 'django.db.backends.mysql',
    
  301.             'USER': 'mysql_user',
    
  302.             'PASSWORD': 'bacon',
    
  303.         },
    
  304.     }
    
  305. 
    
  306. Now we'll need to handle routing. First we want a router that knows to
    
  307. send queries for the ``auth`` and ``contenttypes`` apps to ``auth_db``
    
  308. (``auth`` models are linked to ``ContentType``, so they must be stored in the
    
  309. same database)::
    
  310. 
    
  311.     class AuthRouter:
    
  312.         """
    
  313.         A router to control all database operations on models in the
    
  314.         auth and contenttypes applications.
    
  315.         """
    
  316.         route_app_labels = {'auth', 'contenttypes'}
    
  317. 
    
  318.         def db_for_read(self, model, **hints):
    
  319.             """
    
  320.             Attempts to read auth and contenttypes models go to auth_db.
    
  321.             """
    
  322.             if model._meta.app_label in self.route_app_labels:
    
  323.                 return 'auth_db'
    
  324.             return None
    
  325. 
    
  326.         def db_for_write(self, model, **hints):
    
  327.             """
    
  328.             Attempts to write auth and contenttypes models go to auth_db.
    
  329.             """
    
  330.             if model._meta.app_label in self.route_app_labels:
    
  331.                 return 'auth_db'
    
  332.             return None
    
  333. 
    
  334.         def allow_relation(self, obj1, obj2, **hints):
    
  335.             """
    
  336.             Allow relations if a model in the auth or contenttypes apps is
    
  337.             involved.
    
  338.             """
    
  339.             if (
    
  340.                 obj1._meta.app_label in self.route_app_labels or
    
  341.                 obj2._meta.app_label in self.route_app_labels
    
  342.             ):
    
  343.                return True
    
  344.             return None
    
  345. 
    
  346.         def allow_migrate(self, db, app_label, model_name=None, **hints):
    
  347.             """
    
  348.             Make sure the auth and contenttypes apps only appear in the
    
  349.             'auth_db' database.
    
  350.             """
    
  351.             if app_label in self.route_app_labels:
    
  352.                 return db == 'auth_db'
    
  353.             return None
    
  354. 
    
  355. And we also want a router that sends all other apps to the
    
  356. primary/replica configuration, and randomly chooses a replica to read
    
  357. from::
    
  358. 
    
  359.     import random
    
  360. 
    
  361.     class PrimaryReplicaRouter:
    
  362.         def db_for_read(self, model, **hints):
    
  363.             """
    
  364.             Reads go to a randomly-chosen replica.
    
  365.             """
    
  366.             return random.choice(['replica1', 'replica2'])
    
  367. 
    
  368.         def db_for_write(self, model, **hints):
    
  369.             """
    
  370.             Writes always go to primary.
    
  371.             """
    
  372.             return 'primary'
    
  373. 
    
  374.         def allow_relation(self, obj1, obj2, **hints):
    
  375.             """
    
  376.             Relations between objects are allowed if both objects are
    
  377.             in the primary/replica pool.
    
  378.             """
    
  379.             db_set = {'primary', 'replica1', 'replica2'}
    
  380.             if obj1._state.db in db_set and obj2._state.db in db_set:
    
  381.                 return True
    
  382.             return None
    
  383. 
    
  384.         def allow_migrate(self, db, app_label, model_name=None, **hints):
    
  385.             """
    
  386.             All non-auth models end up in this pool.
    
  387.             """
    
  388.             return True
    
  389. 
    
  390. Finally, in the settings file, we add the following (substituting
    
  391. ``path.to.`` with the actual Python path to the module(s) where the
    
  392. routers are defined)::
    
  393. 
    
  394.     DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']
    
  395. 
    
  396. The order in which routers are processed is significant. Routers will
    
  397. be queried in the order they are listed in the
    
  398. :setting:`DATABASE_ROUTERS` setting. In this example, the
    
  399. ``AuthRouter`` is processed before the ``PrimaryReplicaRouter``, and as a
    
  400. result, decisions concerning the models in ``auth`` are processed
    
  401. before any other decision is made. If the :setting:`DATABASE_ROUTERS`
    
  402. setting listed the two routers in the other order,
    
  403. ``PrimaryReplicaRouter.allow_migrate()`` would be processed first. The
    
  404. catch-all nature of the PrimaryReplicaRouter implementation would mean
    
  405. that all models would be available on all databases.
    
  406. 
    
  407. With this setup installed, and all databases migrated as per
    
  408. :ref:`synchronizing_multiple_databases`, lets run some Django code::
    
  409. 
    
  410.     >>> # This retrieval will be performed on the 'auth_db' database
    
  411.     >>> fred = User.objects.get(username='fred')
    
  412.     >>> fred.first_name = 'Frederick'
    
  413. 
    
  414.     >>> # This save will also be directed to 'auth_db'
    
  415.     >>> fred.save()
    
  416. 
    
  417.     >>> # These retrieval will be randomly allocated to a replica database
    
  418.     >>> dna = Person.objects.get(name='Douglas Adams')
    
  419. 
    
  420.     >>> # A new object has no database allocation when created
    
  421.     >>> mh = Book(title='Mostly Harmless')
    
  422. 
    
  423.     >>> # This assignment will consult the router, and set mh onto
    
  424.     >>> # the same database as the author object
    
  425.     >>> mh.author = dna
    
  426. 
    
  427.     >>> # This save will force the 'mh' instance onto the primary database...
    
  428.     >>> mh.save()
    
  429. 
    
  430.     >>> # ... but if we re-retrieve the object, it will come back on a replica
    
  431.     >>> mh = Book.objects.get(title='Mostly Harmless')
    
  432. 
    
  433. This example defined a router to handle interaction with models from the
    
  434. ``auth`` app, and other routers to handle interaction with all other apps. If
    
  435. you left your ``default`` database empty and don't want to define a catch-all
    
  436. database router to handle all apps not otherwise specified, your routers must
    
  437. handle the names of all apps in :setting:`INSTALLED_APPS` before you migrate.
    
  438. See :ref:`contrib_app_multiple_databases` for information about contrib apps
    
  439. that must be together in one database.
    
  440. 
    
  441. Manually selecting a database
    
  442. =============================
    
  443. 
    
  444. Django also provides an API that allows you to maintain complete control
    
  445. over database usage in your code. A manually specified database allocation
    
  446. will take priority over a database allocated by a router.
    
  447. 
    
  448. Manually selecting a database for a ``QuerySet``
    
  449. ------------------------------------------------
    
  450. 
    
  451. You can select the database for a ``QuerySet`` at any point in the
    
  452. ``QuerySet`` "chain." Call ``using()`` on the ``QuerySet`` to get another
    
  453. ``QuerySet`` that uses the specified database.
    
  454. 
    
  455. ``using()`` takes a single argument: the alias of the database on
    
  456. which you want to run the query. For example::
    
  457. 
    
  458.     >>> # This will run on the 'default' database.
    
  459.     >>> Author.objects.all()
    
  460. 
    
  461.     >>> # So will this.
    
  462.     >>> Author.objects.using('default')
    
  463. 
    
  464.     >>> # This will run on the 'other' database.
    
  465.     >>> Author.objects.using('other')
    
  466. 
    
  467. Selecting a database for ``save()``
    
  468. -----------------------------------
    
  469. 
    
  470. Use the ``using`` keyword to ``Model.save()`` to specify to which
    
  471. database the data should be saved.
    
  472. 
    
  473. For example, to save an object to the ``legacy_users`` database, you'd
    
  474. use this::
    
  475. 
    
  476.     >>> my_object.save(using='legacy_users')
    
  477. 
    
  478. If you don't specify ``using``, the ``save()`` method will save into
    
  479. the default database allocated by the routers.
    
  480. 
    
  481. Moving an object from one database to another
    
  482. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  483. 
    
  484. If you've saved an instance to one database, it might be tempting to
    
  485. use ``save(using=...)`` as a way to migrate the instance to a new
    
  486. database. However, if you don't take appropriate steps, this could
    
  487. have some unexpected consequences.
    
  488. 
    
  489. Consider the following example::
    
  490. 
    
  491.     >>> p = Person(name='Fred')
    
  492.     >>> p.save(using='first')  # (statement 1)
    
  493.     >>> p.save(using='second') # (statement 2)
    
  494. 
    
  495. In statement 1, a new ``Person`` object is saved to the ``first``
    
  496. database. At this time, ``p`` doesn't have a primary key, so Django
    
  497. issues an SQL ``INSERT`` statement. This creates a primary key, and
    
  498. Django assigns that primary key to ``p``.
    
  499. 
    
  500. When the save occurs in statement 2, ``p`` already has a primary key
    
  501. value, and Django will attempt to use that primary key on the new
    
  502. database. If the primary key value isn't in use in the ``second``
    
  503. database, then you won't have any problems -- the object will be
    
  504. copied to the new database.
    
  505. 
    
  506. However, if the primary key of ``p`` is already in use on the
    
  507. ``second`` database, the existing object in the ``second`` database
    
  508. will be overridden when ``p`` is saved.
    
  509. 
    
  510. You can avoid this in two ways. First, you can clear the primary key
    
  511. of the instance. If an object has no primary key, Django will treat it
    
  512. as a new object, avoiding any loss of data on the ``second``
    
  513. database::
    
  514. 
    
  515.     >>> p = Person(name='Fred')
    
  516.     >>> p.save(using='first')
    
  517.     >>> p.pk = None # Clear the primary key.
    
  518.     >>> p.save(using='second') # Write a completely new object.
    
  519. 
    
  520. The second option is to use the ``force_insert`` option to ``save()``
    
  521. to ensure that Django does an SQL ``INSERT``::
    
  522. 
    
  523.     >>> p = Person(name='Fred')
    
  524.     >>> p.save(using='first')
    
  525.     >>> p.save(using='second', force_insert=True)
    
  526. 
    
  527. This will ensure that the person named ``Fred`` will have the same
    
  528. primary key on both databases. If that primary key is already in use
    
  529. when you try to save onto the ``second`` database, an error will be
    
  530. raised.
    
  531. 
    
  532. Selecting a database to delete from
    
  533. -----------------------------------
    
  534. 
    
  535. By default, a call to delete an existing object will be executed on
    
  536. the same database that was used to retrieve the object in the first
    
  537. place::
    
  538. 
    
  539.     >>> u = User.objects.using('legacy_users').get(username='fred')
    
  540.     >>> u.delete() # will delete from the `legacy_users` database
    
  541. 
    
  542. To specify the database from which a model will be deleted, pass a
    
  543. ``using`` keyword argument to the ``Model.delete()`` method. This
    
  544. argument works just like the ``using`` keyword argument to ``save()``.
    
  545. 
    
  546. For example, if you're migrating a user from the ``legacy_users``
    
  547. database to the ``new_users`` database, you might use these commands::
    
  548. 
    
  549.     >>> user_obj.save(using='new_users')
    
  550.     >>> user_obj.delete(using='legacy_users')
    
  551. 
    
  552. Using managers with multiple databases
    
  553. --------------------------------------
    
  554. 
    
  555. Use the ``db_manager()`` method on managers to give managers access to
    
  556. a non-default database.
    
  557. 
    
  558. For example, say you have a custom manager method that touches the
    
  559. database -- ``User.objects.create_user()``. Because ``create_user()``
    
  560. is a manager method, not a ``QuerySet`` method, you can't do
    
  561. ``User.objects.using('new_users').create_user()``. (The
    
  562. ``create_user()`` method is only available on ``User.objects``, the
    
  563. manager, not on ``QuerySet`` objects derived from the manager.) The
    
  564. solution is to use ``db_manager()``, like this::
    
  565. 
    
  566.     User.objects.db_manager('new_users').create_user(...)
    
  567. 
    
  568. ``db_manager()`` returns a copy of the manager bound to the database you specify.
    
  569. 
    
  570. Using ``get_queryset()`` with multiple databases
    
  571. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  572. 
    
  573. If you're overriding ``get_queryset()`` on your manager, be sure to
    
  574. either call the method on the parent (using ``super()``) or do the
    
  575. appropriate handling of the ``_db`` attribute on the manager (a string
    
  576. containing the name of the database to use).
    
  577. 
    
  578. For example, if you want to return a custom ``QuerySet`` class from
    
  579. the ``get_queryset`` method, you could do this::
    
  580. 
    
  581.     class MyManager(models.Manager):
    
  582.         def get_queryset(self):
    
  583.             qs = CustomQuerySet(self.model)
    
  584.             if self._db is not None:
    
  585.                 qs = qs.using(self._db)
    
  586.             return qs
    
  587. 
    
  588. Exposing multiple databases in Django's admin interface
    
  589. =======================================================
    
  590. 
    
  591. Django's admin doesn't have any explicit support for multiple
    
  592. databases. If you want to provide an admin interface for a model on a
    
  593. database other than that specified by your router chain, you'll
    
  594. need to write custom :class:`~django.contrib.admin.ModelAdmin` classes
    
  595. that will direct the admin to use a specific database for content.
    
  596. 
    
  597. ``ModelAdmin`` objects have the following methods that require customization
    
  598. for multiple-database support::
    
  599. 
    
  600.     class MultiDBModelAdmin(admin.ModelAdmin):
    
  601.         # A handy constant for the name of the alternate database.
    
  602.         using = 'other'
    
  603. 
    
  604.         def save_model(self, request, obj, form, change):
    
  605.             # Tell Django to save objects to the 'other' database.
    
  606.             obj.save(using=self.using)
    
  607. 
    
  608.         def delete_model(self, request, obj):
    
  609.             # Tell Django to delete objects from the 'other' database
    
  610.             obj.delete(using=self.using)
    
  611. 
    
  612.         def get_queryset(self, request):
    
  613.             # Tell Django to look for objects on the 'other' database.
    
  614.             return super().get_queryset(request).using(self.using)
    
  615. 
    
  616.         def formfield_for_foreignkey(self, db_field, request, **kwargs):
    
  617.             # Tell Django to populate ForeignKey widgets using a query
    
  618.             # on the 'other' database.
    
  619.             return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
    
  620. 
    
  621.         def formfield_for_manytomany(self, db_field, request, **kwargs):
    
  622.             # Tell Django to populate ManyToMany widgets using a query
    
  623.             # on the 'other' database.
    
  624.             return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
    
  625. 
    
  626. The implementation provided here implements a multi-database strategy
    
  627. where all objects of a given type are stored on a specific database
    
  628. (e.g., all ``User`` objects are in the ``other`` database). If your
    
  629. usage of multiple databases is more complex, your ``ModelAdmin`` will
    
  630. need to reflect that strategy.
    
  631. 
    
  632. :class:`~django.contrib.admin.InlineModelAdmin` objects can be handled in a
    
  633. similar fashion. They require three customized methods::
    
  634. 
    
  635.     class MultiDBTabularInline(admin.TabularInline):
    
  636.         using = 'other'
    
  637. 
    
  638.         def get_queryset(self, request):
    
  639.             # Tell Django to look for inline objects on the 'other' database.
    
  640.             return super().get_queryset(request).using(self.using)
    
  641. 
    
  642.         def formfield_for_foreignkey(self, db_field, request, **kwargs):
    
  643.             # Tell Django to populate ForeignKey widgets using a query
    
  644.             # on the 'other' database.
    
  645.             return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
    
  646. 
    
  647.         def formfield_for_manytomany(self, db_field, request, **kwargs):
    
  648.             # Tell Django to populate ManyToMany widgets using a query
    
  649.             # on the 'other' database.
    
  650.             return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
    
  651. 
    
  652. Once you've written your model admin definitions, they can be
    
  653. registered with any ``Admin`` instance::
    
  654. 
    
  655.     from django.contrib import admin
    
  656. 
    
  657.     # Specialize the multi-db admin objects for use with specific models.
    
  658.     class BookInline(MultiDBTabularInline):
    
  659.         model = Book
    
  660. 
    
  661.     class PublisherAdmin(MultiDBModelAdmin):
    
  662.         inlines = [BookInline]
    
  663. 
    
  664.     admin.site.register(Author, MultiDBModelAdmin)
    
  665.     admin.site.register(Publisher, PublisherAdmin)
    
  666. 
    
  667.     othersite = admin.AdminSite('othersite')
    
  668.     othersite.register(Publisher, MultiDBModelAdmin)
    
  669. 
    
  670. This example sets up two admin sites. On the first site, the
    
  671. ``Author`` and ``Publisher`` objects are exposed; ``Publisher``
    
  672. objects have a tabular inline showing books published by that
    
  673. publisher. The second site exposes just publishers, without the
    
  674. inlines.
    
  675. 
    
  676. Using raw cursors with multiple databases
    
  677. =========================================
    
  678. 
    
  679. If you are using more than one database you can use
    
  680. ``django.db.connections`` to obtain the connection (and cursor) for a
    
  681. specific database. ``django.db.connections`` is a dictionary-like
    
  682. object that allows you to retrieve a specific connection using its
    
  683. alias::
    
  684. 
    
  685.     from django.db import connections
    
  686.     with connections['my_db_alias'].cursor() as cursor:
    
  687.         ...
    
  688. 
    
  689. Limitations of multiple databases
    
  690. =================================
    
  691. 
    
  692. .. _no_cross_database_relations:
    
  693. 
    
  694. Cross-database relations
    
  695. ------------------------
    
  696. 
    
  697. Django doesn't currently provide any support for foreign key or
    
  698. many-to-many relationships spanning multiple databases. If you
    
  699. have used a router to partition models to different databases,
    
  700. any foreign key and many-to-many relationships defined by those
    
  701. models must be internal to a single database.
    
  702. 
    
  703. This is because of referential integrity. In order to maintain a
    
  704. relationship between two objects, Django needs to know that the
    
  705. primary key of the related object is valid. If the primary key is
    
  706. stored on a separate database, it's not possible to easily evaluate
    
  707. the validity of a primary key.
    
  708. 
    
  709. If you're using Postgres, Oracle, or MySQL with InnoDB, this is
    
  710. enforced at the database integrity level -- database level key
    
  711. constraints prevent the creation of relations that can't be validated.
    
  712. 
    
  713. However, if you're using SQLite or MySQL with MyISAM tables, there is
    
  714. no enforced referential integrity; as a result, you may be able to
    
  715. 'fake' cross database foreign keys. However, this configuration is not
    
  716. officially supported by Django.
    
  717. 
    
  718. .. _contrib_app_multiple_databases:
    
  719. 
    
  720. Behavior of contrib apps
    
  721. ------------------------
    
  722. 
    
  723. Several contrib apps include models, and some apps depend on others. Since
    
  724. cross-database relationships are impossible, this creates some restrictions on
    
  725. how you can split these models across databases:
    
  726. 
    
  727. - each one of ``contenttypes.ContentType``, ``sessions.Session`` and
    
  728.   ``sites.Site`` can be stored in any database, given a suitable router.
    
  729. - ``auth`` models — ``User``, ``Group`` and ``Permission`` — are linked
    
  730.   together and linked to ``ContentType``, so they must be stored in the same
    
  731.   database as ``ContentType``.
    
  732. - ``admin`` depends on ``auth``, so its models must be in the same database
    
  733.   as ``auth``.
    
  734. - ``flatpages`` and ``redirects`` depend on ``sites``, so their models must be
    
  735.   in the same database as ``sites``.
    
  736. 
    
  737. In addition, some objects are automatically created just after
    
  738. :djadmin:`migrate` creates a table to hold them in a database:
    
  739. 
    
  740. - a default ``Site``,
    
  741. - a ``ContentType`` for each model (including those not stored in that
    
  742.   database),
    
  743. - the ``Permission``\s for each model (including those not stored in that
    
  744.   database).
    
  745. 
    
  746. For common setups with multiple databases, it isn't useful to have these
    
  747. objects in more than one database. Common setups include primary/replica and
    
  748. connecting to external databases. Therefore, it's recommended to write a
    
  749. :ref:`database router<topics-db-multi-db-routing>` that allows synchronizing
    
  750. these three models to only one database. Use the same approach for contrib
    
  751. and third-party apps that don't need their tables in multiple databases.
    
  752. 
    
  753. .. warning::
    
  754. 
    
  755.     If you're synchronizing content types to more than one database, be aware
    
  756.     that their primary keys may not match across databases. This may result in
    
  757.     data corruption or data loss.