2009-12-22 15:18:51 +00:00
|
|
|
==================
|
2010-01-09 17:09:20 +00:00
|
|
|
Multiple databases
|
2009-12-22 15:18:51 +00:00
|
|
|
==================
|
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
This topic guide describes Django's support for interacting with
|
|
|
|
multiple databases. Most of the rest of Django's documentation assumes
|
|
|
|
you are interacting with a single database. If you want to interact
|
|
|
|
with multiple databases, you'll need to take some additional steps.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2018-06-29 00:29:07 +00:00
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
See :ref:`testing-multi-db` for information about testing with multiple
|
|
|
|
databases.
|
|
|
|
|
2009-12-22 15:18:51 +00:00
|
|
|
Defining your databases
|
|
|
|
=======================
|
|
|
|
|
|
|
|
The first step to using more than one database with Django is to tell
|
|
|
|
Django about the database servers you'll be using. This is done using
|
|
|
|
the :setting:`DATABASES` setting. This setting maps database aliases,
|
|
|
|
which are a way to refer to a specific database throughout Django, to
|
|
|
|
a dictionary of settings for that specific connection. The settings in
|
|
|
|
the inner dictionaries are described fully in the :setting:`DATABASES`
|
|
|
|
documentation.
|
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Databases can have any alias you choose. However, the alias
|
|
|
|
``default`` has special significance. Django uses the database with
|
2013-02-23 21:01:43 +00:00
|
|
|
the alias of ``default`` when no other database has been selected.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
The following is an example ``settings.py`` snippet defining two
|
2010-01-09 17:09:20 +00:00
|
|
|
databases -- a default PostgreSQL database and a MySQL database called
|
2014-08-18 14:30:44 +00:00
|
|
|
``users``::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
DATABASES = {
|
|
|
|
'default': {
|
|
|
|
'NAME': 'app_data',
|
2015-08-05 14:08:56 +00:00
|
|
|
'ENGINE': 'django.db.backends.postgresql',
|
2009-12-22 15:18:51 +00:00
|
|
|
'USER': 'postgres_user',
|
|
|
|
'PASSWORD': 's3krit'
|
|
|
|
},
|
|
|
|
'users': {
|
2010-02-21 23:37:19 +00:00
|
|
|
'NAME': 'user_data',
|
2009-12-25 10:26:36 +00:00
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
2009-12-22 15:18:51 +00:00
|
|
|
'USER': 'mysql_user',
|
|
|
|
'PASSWORD': 'priv4te'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-02-23 21:01:43 +00:00
|
|
|
If the concept of a ``default`` database doesn't make sense in the context
|
|
|
|
of your project, you need to be careful to always specify the database
|
|
|
|
that you want to use. Django requires that a ``default`` database entry
|
|
|
|
be defined, but the parameters dictionary can be left blank if it will not be
|
2016-08-02 23:55:57 +00:00
|
|
|
used. To do this, you must set up :setting:`DATABASE_ROUTERS` for all of your
|
|
|
|
apps' models, including those in any contrib and third-party apps you're using,
|
|
|
|
so that no queries are routed to the default database. The following is an
|
|
|
|
example ``settings.py`` snippet defining two non-default databases, with the
|
|
|
|
``default`` entry intentionally left empty::
|
2013-02-23 21:01:43 +00:00
|
|
|
|
|
|
|
DATABASES = {
|
|
|
|
'default': {},
|
|
|
|
'users': {
|
|
|
|
'NAME': 'user_data',
|
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
|
|
|
'USER': 'mysql_user',
|
|
|
|
'PASSWORD': 'superS3cret'
|
|
|
|
},
|
|
|
|
'customers': {
|
|
|
|
'NAME': 'customer_data',
|
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
|
|
|
'USER': 'mysql_cust',
|
|
|
|
'PASSWORD': 'veryPriv@ate'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-12-22 15:18:51 +00:00
|
|
|
If you attempt to access a database that you haven't defined in your
|
2010-01-09 17:09:20 +00:00
|
|
|
:setting:`DATABASES` setting, Django will raise a
|
2017-10-22 15:30:42 +00:00
|
|
|
``django.utils.connection.ConnectionDoesNotExist`` exception.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2020-10-08 10:45:06 +00:00
|
|
|
.. _synchronizing_multiple_databases:
|
|
|
|
|
2010-01-07 11:37:49 +00:00
|
|
|
Synchronizing your databases
|
|
|
|
============================
|
|
|
|
|
2013-11-21 14:04:31 +00:00
|
|
|
The :djadmin:`migrate` management command operates on one database at a
|
2010-01-07 11:37:49 +00:00
|
|
|
time. By default, it operates on the ``default`` database, but by
|
2016-01-12 01:59:34 +00:00
|
|
|
providing the :option:`--database <migrate --database>` option, you can tell it
|
2013-11-21 14:04:31 +00:00
|
|
|
to synchronize a different database. So, to synchronize all models onto
|
2016-08-02 23:55:57 +00:00
|
|
|
all databases in the first example above, you would need to call::
|
2010-01-07 11:37:49 +00:00
|
|
|
|
2013-11-21 14:04:31 +00:00
|
|
|
$ ./manage.py migrate
|
|
|
|
$ ./manage.py migrate --database=users
|
2010-01-07 11:37:49 +00:00
|
|
|
|
|
|
|
If you don't want every application to be synchronized onto a
|
2010-01-25 12:23:30 +00:00
|
|
|
particular database, you can define a :ref:`database
|
|
|
|
router<topics-db-multi-db-routing>` that implements a policy
|
|
|
|
constraining the availability of particular models.
|
2010-01-07 11:37:49 +00:00
|
|
|
|
2016-08-02 23:55:57 +00:00
|
|
|
If, as in the second example above, you've left the ``default`` database empty,
|
|
|
|
you must provide a database name each time you run :djadmin:`migrate`. Omitting
|
|
|
|
the database name would raise an error. For the second example::
|
|
|
|
|
|
|
|
$ ./manage.py migrate --database=users
|
|
|
|
$ ./manage.py migrate --database=customers
|
|
|
|
|
2010-01-07 11:37:49 +00:00
|
|
|
Using other management commands
|
|
|
|
-------------------------------
|
|
|
|
|
2016-09-01 20:19:47 +00:00
|
|
|
Most other ``django-admin`` commands that interact with the database operate in
|
2016-01-12 01:59:34 +00:00
|
|
|
the same way as :djadmin:`migrate` -- they only ever operate on one database at
|
|
|
|
a time, using ``--database`` to control the database used.
|
2010-01-07 11:37:49 +00:00
|
|
|
|
2016-09-01 20:19:47 +00:00
|
|
|
An exception to this rule is the :djadmin:`makemigrations` command. It
|
|
|
|
validates the migration history in the databases to catch problems with the
|
|
|
|
existing migration files (which could be caused by editing them) before
|
|
|
|
creating new migrations. By default, it checks only the ``default`` database,
|
2016-11-11 17:40:06 +00:00
|
|
|
but it consults the :meth:`allow_migrate` method of :ref:`routers
|
2016-09-01 20:19:47 +00:00
|
|
|
<topics-db-multi-db-routing>` if any are installed.
|
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
.. _topics-db-multi-db-routing:
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Automatic database routing
|
|
|
|
==========================
|
2010-01-09 17:09:20 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
The easiest way to use multiple databases is to set up a database
|
|
|
|
routing scheme. The default routing scheme ensures that objects remain
|
|
|
|
'sticky' to their original database (i.e., an object retrieved from
|
2010-01-28 03:04:24 +00:00
|
|
|
the ``foo`` database will be saved on the same database). The default
|
|
|
|
routing scheme ensures that if a database isn't specified, all queries
|
|
|
|
fall back to the ``default`` database.
|
|
|
|
|
|
|
|
You don't have to do anything to activate the default routing scheme
|
|
|
|
-- it is provided 'out of the box' on every Django project. However,
|
|
|
|
if you want to implement more interesting database allocation
|
|
|
|
behaviors, you can define and install your own database routers.
|
2009-12-22 16:10:48 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Database routers
|
|
|
|
----------------
|
|
|
|
|
2010-01-27 07:56:53 +00:00
|
|
|
A database Router is a class that provides up to four methods:
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
.. method:: db_for_read(model, **hints)
|
|
|
|
|
|
|
|
Suggest the database that should be used for read operations for
|
|
|
|
objects of type ``model``.
|
|
|
|
|
|
|
|
If a database operation is able to provide any additional
|
|
|
|
information that might assist in selecting a database, it will be
|
|
|
|
provided in the ``hints`` dictionary. Details on valid hints are
|
|
|
|
provided :ref:`below <topics-db-multi-db-hints>`.
|
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
Returns ``None`` if there is no suggestion.
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
.. method:: db_for_write(model, **hints)
|
|
|
|
|
|
|
|
Suggest the database that should be used for writes of objects of
|
|
|
|
type Model.
|
|
|
|
|
|
|
|
If a database operation is able to provide any additional
|
|
|
|
information that might assist in selecting a database, it will be
|
|
|
|
provided in the ``hints`` dictionary. Details on valid hints are
|
|
|
|
provided :ref:`below <topics-db-multi-db-hints>`.
|
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
Returns ``None`` if there is no suggestion.
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
.. method:: allow_relation(obj1, obj2, **hints)
|
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
Return ``True`` if a relation between ``obj1`` and ``obj2`` should be
|
|
|
|
allowed, ``False`` if the relation should be prevented, or ``None`` if
|
2010-01-22 14:30:06 +00:00
|
|
|
the router has no opinion. This is purely a validation operation,
|
|
|
|
used by foreign key and many to many operations to determine if a
|
|
|
|
relation should be allowed between two objects.
|
|
|
|
|
2018-04-21 13:42:14 +00:00
|
|
|
If no router has an opinion (i.e. all routers return ``None``), only
|
|
|
|
relations within the same database are allowed.
|
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
.. method:: allow_migrate(db, app_label, model_name=None, **hints)
|
2010-01-25 12:23:30 +00:00
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
Determine if the migration operation is allowed to run on the database with
|
|
|
|
alias ``db``. Return ``True`` if the operation should run, ``False`` if it
|
|
|
|
shouldn't run, or ``None`` if the router has no opinion.
|
2010-01-25 12:23:30 +00:00
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
The ``app_label`` positional argument is the label of the application
|
|
|
|
being migrated.
|
2013-07-30 11:34:31 +00:00
|
|
|
|
2015-02-19 07:27:58 +00:00
|
|
|
``model_name`` is set by most migration operations to the value of
|
|
|
|
``model._meta.model_name`` (the lowercased version of the model
|
|
|
|
``__name__``) of the model being migrated. Its value is ``None`` for the
|
|
|
|
:class:`~django.db.migrations.operations.RunPython` and
|
|
|
|
:class:`~django.db.migrations.operations.RunSQL` operations unless they
|
|
|
|
provide it using hints.
|
|
|
|
|
|
|
|
``hints`` are used by certain operations to communicate additional
|
|
|
|
information to the router.
|
|
|
|
|
|
|
|
When ``model_name`` is set, ``hints`` normally contains the model class
|
|
|
|
under the key ``'model'``. Note that it may be a :ref:`historical model
|
|
|
|
<historical-models>`, and thus not have any custom attributes, methods, or
|
|
|
|
managers. You should only rely on ``_meta``.
|
|
|
|
|
|
|
|
This method can also be used to determine the availability of a model on a
|
|
|
|
given database.
|
|
|
|
|
2016-08-15 17:34:54 +00:00
|
|
|
:djadmin:`makemigrations` always creates migrations for model changes, but
|
|
|
|
if ``allow_migrate()`` returns ``False``, any migration operations for the
|
|
|
|
``model_name`` will be silently skipped when running :djadmin:`migrate` on
|
|
|
|
the ``db``. Changing the behavior of ``allow_migrate()`` for models that
|
|
|
|
already have migrations may result in broken foreign keys, extra tables,
|
2016-09-01 20:19:47 +00:00
|
|
|
or missing tables. When :djadmin:`makemigrations` verifies the migration
|
|
|
|
history, it skips databases where no app is allowed to migrate.
|
2015-02-19 07:27:58 +00:00
|
|
|
|
2011-03-26 03:54:53 +00:00
|
|
|
A router doesn't have to provide *all* these methods -- it may omit one
|
|
|
|
or more of them. If one of the methods is omitted, Django will skip
|
|
|
|
that router when performing the relevant check.
|
2010-01-27 07:56:53 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
.. _topics-db-multi-db-hints:
|
|
|
|
|
|
|
|
Hints
|
|
|
|
~~~~~
|
|
|
|
|
|
|
|
The hints received by the database router can be used to decide which
|
|
|
|
database should receive a given request.
|
|
|
|
|
|
|
|
At present, the only hint that will be provided is ``instance``, an
|
|
|
|
object instance that is related to the read or write operation that is
|
|
|
|
underway. This might be the instance that is being saved, or it might
|
|
|
|
be an instance that is being added in a many-to-many relation. In some
|
2010-01-23 04:32:34 +00:00
|
|
|
cases, no instance hint will be provided at all. The router checks for
|
|
|
|
the existence of an instance hint, and determine if that hint should be
|
2010-01-22 14:30:06 +00:00
|
|
|
used to alter routing behavior.
|
|
|
|
|
|
|
|
Using routers
|
|
|
|
-------------
|
|
|
|
|
|
|
|
Database routers are installed using the :setting:`DATABASE_ROUTERS`
|
|
|
|
setting. This setting defines a list of class names, each specifying a
|
2014-05-20 19:54:56 +00:00
|
|
|
router that should be used by the master router
|
2010-01-22 14:30:06 +00:00
|
|
|
(``django.db.router``).
|
|
|
|
|
2014-05-20 19:54:56 +00:00
|
|
|
The master router is used by Django's database operations to allocate
|
2010-01-22 14:30:06 +00:00
|
|
|
database usage. Whenever a query needs to know which database to use,
|
2014-05-20 19:54:56 +00:00
|
|
|
it calls the master router, providing a model and a hint (if
|
2010-01-22 14:30:06 +00:00
|
|
|
available). Django then tries each router in turn until a database
|
|
|
|
suggestion can be found. If no suggestion can be found, it tries the
|
2020-07-15 09:27:46 +00:00
|
|
|
current :attr:`instance._state.db <django.db.models.Model._state>` of the hint
|
|
|
|
instance. If a hint instance wasn't provided, or :attr:`instance._state.db
|
|
|
|
<django.db.models.Model._state>` is ``None``, the master router will allocate
|
|
|
|
the ``default`` database.
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
An example
|
|
|
|
----------
|
|
|
|
|
|
|
|
.. admonition:: Example purposes only!
|
|
|
|
|
|
|
|
This example is intended as a demonstration of how the router
|
|
|
|
infrastructure can be used to alter database usage. It
|
|
|
|
intentionally ignores some complex issues in order to
|
|
|
|
demonstrate how routers are used.
|
|
|
|
|
2010-05-09 07:44:06 +00:00
|
|
|
This example won't work if any of the models in ``myapp`` contain
|
|
|
|
relationships to models outside of the ``other`` database.
|
|
|
|
:ref:`Cross-database relationships <no_cross_database_relations>`
|
|
|
|
introduce referential integrity problems that Django can't
|
|
|
|
currently handle.
|
2010-01-22 14:30:06 +00:00
|
|
|
|
2014-05-20 19:54:56 +00:00
|
|
|
The primary/replica (referred to as master/slave by some databases)
|
|
|
|
configuration described is also flawed -- it
|
2010-01-22 14:30:06 +00:00
|
|
|
doesn't provide any solution for handling replication lag (i.e.,
|
|
|
|
query inconsistencies introduced because of the time taken for a
|
2014-05-20 19:54:56 +00:00
|
|
|
write to propagate to the replicas). It also doesn't consider the
|
2010-01-23 04:32:34 +00:00
|
|
|
interaction of transactions with the database utilization strategy.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2012-09-08 20:02:00 +00:00
|
|
|
So - what does this mean in practice? Let's consider another sample
|
|
|
|
configuration. This one will have several databases: one for the
|
2014-05-20 19:54:56 +00:00
|
|
|
``auth`` application, and all other apps using a primary/replica setup
|
|
|
|
with two read replicas. Here are the settings specifying these
|
2012-09-08 20:02:00 +00:00
|
|
|
databases::
|
2010-01-22 14:30:06 +00:00
|
|
|
|
2012-09-08 20:02:00 +00:00
|
|
|
DATABASES = {
|
2015-11-06 12:18:18 +00:00
|
|
|
'default': {},
|
2012-09-08 20:02:00 +00:00
|
|
|
'auth_db': {
|
2019-07-29 04:24:43 +00:00
|
|
|
'NAME': 'auth_db_name',
|
2012-09-08 20:02:00 +00:00
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
|
|
|
'USER': 'mysql_user',
|
|
|
|
'PASSWORD': 'swordfish',
|
|
|
|
},
|
2014-05-20 19:54:56 +00:00
|
|
|
'primary': {
|
2019-07-29 04:24:43 +00:00
|
|
|
'NAME': 'primary_name',
|
2012-09-08 20:02:00 +00:00
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
|
|
|
'USER': 'mysql_user',
|
|
|
|
'PASSWORD': 'spam',
|
|
|
|
},
|
2014-05-20 19:54:56 +00:00
|
|
|
'replica1': {
|
2019-07-29 04:24:43 +00:00
|
|
|
'NAME': 'replica1_name',
|
2012-09-08 20:02:00 +00:00
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
|
|
|
'USER': 'mysql_user',
|
|
|
|
'PASSWORD': 'eggs',
|
|
|
|
},
|
2014-05-20 19:54:56 +00:00
|
|
|
'replica2': {
|
2019-07-29 04:24:43 +00:00
|
|
|
'NAME': 'replica2_name',
|
2012-09-08 20:02:00 +00:00
|
|
|
'ENGINE': 'django.db.backends.mysql',
|
|
|
|
'USER': 'mysql_user',
|
|
|
|
'PASSWORD': 'bacon',
|
|
|
|
},
|
|
|
|
}
|
2010-01-22 14:30:06 +00:00
|
|
|
|
2012-09-08 20:02:00 +00:00
|
|
|
Now we'll need to handle routing. First we want a router that knows to
|
2019-11-18 12:35:31 +00:00
|
|
|
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)::
|
2012-09-08 20:02:00 +00:00
|
|
|
|
2017-06-26 14:30:31 +00:00
|
|
|
class AuthRouter:
|
2012-09-08 20:02:00 +00:00
|
|
|
"""
|
|
|
|
A router to control all database operations on models in the
|
2019-11-18 12:35:31 +00:00
|
|
|
auth and contenttypes applications.
|
2012-09-08 20:02:00 +00:00
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
route_app_labels = {'auth', 'contenttypes'}
|
|
|
|
|
2012-09-08 20:08:01 +00:00
|
|
|
def db_for_read(self, model, **hints):
|
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
Attempts to read auth and contenttypes models go to auth_db.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
if model._meta.app_label in self.route_app_labels:
|
2012-09-08 20:08:01 +00:00
|
|
|
return 'auth_db'
|
|
|
|
return None
|
|
|
|
|
|
|
|
def db_for_write(self, model, **hints):
|
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
Attempts to write auth and contenttypes models go to auth_db.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
if model._meta.app_label in self.route_app_labels:
|
2012-09-08 20:08:01 +00:00
|
|
|
return 'auth_db'
|
2012-09-08 20:14:13 +00:00
|
|
|
return None
|
2012-09-08 20:08:01 +00:00
|
|
|
|
|
|
|
def allow_relation(self, obj1, obj2, **hints):
|
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
Allow relations if a model in the auth or contenttypes apps is
|
|
|
|
involved.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
if (
|
|
|
|
obj1._meta.app_label in self.route_app_labels or
|
|
|
|
obj2._meta.app_label in self.route_app_labels
|
|
|
|
):
|
2012-09-08 20:08:01 +00:00
|
|
|
return True
|
|
|
|
return None
|
|
|
|
|
2016-02-09 23:01:08 +00:00
|
|
|
def allow_migrate(self, db, app_label, model_name=None, **hints):
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
Make sure the auth and contenttypes apps only appear in the
|
|
|
|
'auth_db' database.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2019-11-18 12:35:31 +00:00
|
|
|
if app_label in self.route_app_labels:
|
2015-02-19 07:27:58 +00:00
|
|
|
return db == 'auth_db'
|
2012-09-08 20:08:01 +00:00
|
|
|
return None
|
2012-09-08 20:02:00 +00:00
|
|
|
|
|
|
|
And we also want a router that sends all other apps to the
|
2014-05-20 19:54:56 +00:00
|
|
|
primary/replica configuration, and randomly chooses a replica to read
|
2012-09-08 20:02:00 +00:00
|
|
|
from::
|
|
|
|
|
|
|
|
import random
|
2010-01-22 14:30:06 +00:00
|
|
|
|
2017-06-26 14:30:31 +00:00
|
|
|
class PrimaryReplicaRouter:
|
2010-01-22 14:30:06 +00:00
|
|
|
def db_for_read(self, model, **hints):
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2014-05-20 19:54:56 +00:00
|
|
|
Reads go to a randomly-chosen replica.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2014-05-20 19:54:56 +00:00
|
|
|
return random.choice(['replica1', 'replica2'])
|
2012-09-08 20:08:01 +00:00
|
|
|
|
|
|
|
def db_for_write(self, model, **hints):
|
|
|
|
"""
|
2014-05-20 19:54:56 +00:00
|
|
|
Writes always go to primary.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2014-05-20 19:54:56 +00:00
|
|
|
return 'primary'
|
2012-09-08 20:08:01 +00:00
|
|
|
|
|
|
|
def allow_relation(self, obj1, obj2, **hints):
|
|
|
|
"""
|
|
|
|
Relations between objects are allowed if both objects are
|
2014-05-20 19:54:56 +00:00
|
|
|
in the primary/replica pool.
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
2020-06-01 08:20:00 +00:00
|
|
|
db_set = {'primary', 'replica1', 'replica2'}
|
|
|
|
if obj1._state.db in db_set and obj2._state.db in db_set:
|
2012-09-08 20:08:01 +00:00
|
|
|
return True
|
|
|
|
return None
|
|
|
|
|
2016-02-09 23:01:08 +00:00
|
|
|
def allow_migrate(self, db, app_label, model_name=None, **hints):
|
2012-09-08 20:08:01 +00:00
|
|
|
"""
|
|
|
|
All non-auth models end up in this pool.
|
|
|
|
"""
|
|
|
|
return True
|
2012-09-08 20:02:00 +00:00
|
|
|
|
|
|
|
Finally, in the settings file, we add the following (substituting
|
2015-06-05 12:24:53 +00:00
|
|
|
``path.to.`` with the actual Python path to the module(s) where the
|
2012-09-08 20:02:00 +00:00
|
|
|
routers are defined)::
|
|
|
|
|
2014-05-20 19:54:56 +00:00
|
|
|
DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']
|
2010-01-22 14:30:06 +00:00
|
|
|
|
2010-01-25 12:23:30 +00:00
|
|
|
The order in which routers are processed is significant. Routers will
|
2016-08-02 23:55:57 +00:00
|
|
|
be queried in the order they are listed in the
|
|
|
|
:setting:`DATABASE_ROUTERS` setting. In this example, the
|
2014-05-20 19:54:56 +00:00
|
|
|
``AuthRouter`` is processed before the ``PrimaryReplicaRouter``, and as a
|
2012-09-08 20:02:00 +00:00
|
|
|
result, decisions concerning the models in ``auth`` are processed
|
2010-01-25 12:23:30 +00:00
|
|
|
before any other decision is made. If the :setting:`DATABASE_ROUTERS`
|
|
|
|
setting listed the two routers in the other order,
|
2014-05-20 19:54:56 +00:00
|
|
|
``PrimaryReplicaRouter.allow_migrate()`` would be processed first. The
|
|
|
|
catch-all nature of the PrimaryReplicaRouter implementation would mean
|
2010-01-25 12:23:30 +00:00
|
|
|
that all models would be available on all databases.
|
|
|
|
|
2020-10-08 10:45:06 +00:00
|
|
|
With this setup installed, and all databases migrated as per
|
|
|
|
:ref:`synchronizing_multiple_databases`, lets run some Django code::
|
2010-01-22 14:30:06 +00:00
|
|
|
|
2012-09-08 20:02:00 +00:00
|
|
|
>>> # This retrieval will be performed on the 'auth_db' database
|
2010-01-22 14:30:06 +00:00
|
|
|
>>> fred = User.objects.get(username='fred')
|
|
|
|
>>> fred.first_name = 'Frederick'
|
|
|
|
|
2012-09-08 20:02:00 +00:00
|
|
|
>>> # This save will also be directed to 'auth_db'
|
2010-01-22 14:30:06 +00:00
|
|
|
>>> fred.save()
|
|
|
|
|
2014-05-20 19:54:56 +00:00
|
|
|
>>> # These retrieval will be randomly allocated to a replica database
|
2010-01-22 14:30:06 +00:00
|
|
|
>>> dna = Person.objects.get(name='Douglas Adams')
|
|
|
|
|
|
|
|
>>> # A new object has no database allocation when created
|
|
|
|
>>> mh = Book(title='Mostly Harmless')
|
|
|
|
|
|
|
|
>>> # This assignment will consult the router, and set mh onto
|
|
|
|
>>> # the same database as the author object
|
|
|
|
>>> mh.author = dna
|
|
|
|
|
2014-05-20 19:54:56 +00:00
|
|
|
>>> # This save will force the 'mh' instance onto the primary database...
|
2010-01-22 14:30:06 +00:00
|
|
|
>>> mh.save()
|
|
|
|
|
2014-05-20 19:54:56 +00:00
|
|
|
>>> # ... but if we re-retrieve the object, it will come back on a replica
|
2010-01-22 14:30:06 +00:00
|
|
|
>>> mh = Book.objects.get(title='Mostly Harmless')
|
|
|
|
|
2016-08-02 23:55:57 +00:00
|
|
|
This example defined a router to handle interaction with models from the
|
|
|
|
``auth`` app, and other routers to handle interaction with all other apps. If
|
|
|
|
you left your ``default`` database empty and don't want to define a catch-all
|
|
|
|
database router to handle all apps not otherwise specified, your routers must
|
|
|
|
handle the names of all apps in :setting:`INSTALLED_APPS` before you migrate.
|
|
|
|
See :ref:`contrib_app_multiple_databases` for information about contrib apps
|
|
|
|
that must be together in one database.
|
2010-01-25 12:23:30 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Manually selecting a database
|
|
|
|
=============================
|
|
|
|
|
|
|
|
Django also provides an API that allows you to maintain complete control
|
|
|
|
over database usage in your code. A manually specified database allocation
|
|
|
|
will take priority over a database allocated by a router.
|
|
|
|
|
|
|
|
Manually selecting a database for a ``QuerySet``
|
|
|
|
------------------------------------------------
|
|
|
|
|
|
|
|
You can select the database for a ``QuerySet`` at any point in the
|
2019-06-17 14:54:55 +00:00
|
|
|
``QuerySet`` "chain." Call ``using()`` on the ``QuerySet`` to get another
|
|
|
|
``QuerySet`` that uses the specified database.
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
``using()`` takes a single argument: the alias of the database on
|
|
|
|
which you want to run the query. For example::
|
|
|
|
|
|
|
|
>>> # This will run on the 'default' database.
|
2009-12-22 15:18:51 +00:00
|
|
|
>>> Author.objects.all()
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
>>> # So will this.
|
2009-12-22 15:18:51 +00:00
|
|
|
>>> Author.objects.using('default').all()
|
2010-01-22 14:30:06 +00:00
|
|
|
|
|
|
|
>>> # This will run on the 'other' database.
|
2009-12-22 15:18:51 +00:00
|
|
|
>>> Author.objects.using('other').all()
|
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
Selecting a database for ``save()``
|
2010-01-22 14:30:06 +00:00
|
|
|
-----------------------------------
|
2010-01-09 17:09:20 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Use the ``using`` keyword to ``Model.save()`` to specify to which
|
|
|
|
database the data should be saved.
|
2010-01-09 17:09:20 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
For example, to save an object to the ``legacy_users`` database, you'd
|
|
|
|
use this::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
>>> my_object.save(using='legacy_users')
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
If you don't specify ``using``, the ``save()`` method will save into
|
|
|
|
the default database allocated by the routers.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
Moving an object from one database to another
|
2010-01-22 14:30:06 +00:00
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
If you've saved an instance to one database, it might be tempting to
|
|
|
|
use ``save(using=...)`` as a way to migrate the instance to a new
|
|
|
|
database. However, if you don't take appropriate steps, this could
|
|
|
|
have some unexpected consequences.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
Consider the following example::
|
|
|
|
|
|
|
|
>>> p = Person(name='Fred')
|
2010-01-09 17:09:20 +00:00
|
|
|
>>> p.save(using='first') # (statement 1)
|
|
|
|
>>> p.save(using='second') # (statement 2)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
In statement 1, a new ``Person`` object is saved to the ``first``
|
2009-12-22 15:18:51 +00:00
|
|
|
database. At this time, ``p`` doesn't have a primary key, so Django
|
2013-09-05 22:23:48 +00:00
|
|
|
issues an SQL ``INSERT`` statement. This creates a primary key, and
|
2009-12-22 15:18:51 +00:00
|
|
|
Django assigns that primary key to ``p``.
|
|
|
|
|
|
|
|
When the save occurs in statement 2, ``p`` already has a primary key
|
|
|
|
value, and Django will attempt to use that primary key on the new
|
|
|
|
database. If the primary key value isn't in use in the ``second``
|
|
|
|
database, then you won't have any problems -- the object will be
|
2010-01-09 17:09:20 +00:00
|
|
|
copied to the new database.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
However, if the primary key of ``p`` is already in use on the
|
2010-01-09 17:09:20 +00:00
|
|
|
``second`` database, the existing object in the ``second`` database
|
|
|
|
will be overridden when ``p`` is saved.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
You can avoid this in two ways. First, you can clear the primary key
|
2010-01-22 14:30:06 +00:00
|
|
|
of the instance. If an object has no primary key, Django will treat it
|
|
|
|
as a new object, avoiding any loss of data on the ``second``
|
|
|
|
database::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
>>> p = Person(name='Fred')
|
|
|
|
>>> p.save(using='first')
|
2010-01-09 17:09:20 +00:00
|
|
|
>>> p.pk = None # Clear the primary key.
|
|
|
|
>>> p.save(using='second') # Write a completely new object.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
The second option is to use the ``force_insert`` option to ``save()``
|
2013-09-05 22:23:48 +00:00
|
|
|
to ensure that Django does an SQL ``INSERT``::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
>>> p = Person(name='Fred')
|
|
|
|
>>> p.save(using='first')
|
|
|
|
>>> p.save(using='second', force_insert=True)
|
|
|
|
|
|
|
|
This will ensure that the person named ``Fred`` will have the same
|
|
|
|
primary key on both databases. If that primary key is already in use
|
|
|
|
when you try to save onto the ``second`` database, an error will be
|
|
|
|
raised.
|
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
Selecting a database to delete from
|
2010-01-22 14:30:06 +00:00
|
|
|
-----------------------------------
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
By default, a call to delete an existing object will be executed on
|
|
|
|
the same database that was used to retrieve the object in the first
|
|
|
|
place::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
>>> u = User.objects.using('legacy_users').get(username='fred')
|
|
|
|
>>> u.delete() # will delete from the `legacy_users` database
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
To specify the database from which a model will be deleted, pass a
|
2010-01-22 14:30:06 +00:00
|
|
|
``using`` keyword argument to the ``Model.delete()`` method. This
|
|
|
|
argument works just like the ``using`` keyword argument to ``save()``.
|
2010-01-09 17:09:20 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
For example, if you're migrating a user from the ``legacy_users``
|
|
|
|
database to the ``new_users`` database, you might use these commands::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
>>> user_obj.save(using='new_users')
|
|
|
|
>>> user_obj.delete(using='legacy_users')
|
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
Using managers with multiple databases
|
2010-01-22 14:30:06 +00:00
|
|
|
--------------------------------------
|
2010-01-09 17:09:20 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Use the ``db_manager()`` method on managers to give managers access to
|
|
|
|
a non-default database.
|
2010-01-09 17:09:20 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
For example, say you have a custom manager method that touches the
|
|
|
|
database -- ``User.objects.create_user()``. Because ``create_user()``
|
|
|
|
is a manager method, not a ``QuerySet`` method, you can't do
|
|
|
|
``User.objects.using('new_users').create_user()``. (The
|
|
|
|
``create_user()`` method is only available on ``User.objects``, the
|
|
|
|
manager, not on ``QuerySet`` objects derived from the manager.) The
|
|
|
|
solution is to use ``db_manager()``, like this::
|
2010-01-09 17:09:20 +00:00
|
|
|
|
|
|
|
User.objects.db_manager('new_users').create_user(...)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
``db_manager()`` returns a copy of the manager bound to the database you specify.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2013-03-08 14:15:23 +00:00
|
|
|
Using ``get_queryset()`` with multiple databases
|
2017-03-20 22:30:32 +00:00
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2013-03-08 14:15:23 +00:00
|
|
|
If you're overriding ``get_queryset()`` on your manager, be sure to
|
2010-01-22 14:30:06 +00:00
|
|
|
either call the method on the parent (using ``super()``) or do the
|
|
|
|
appropriate handling of the ``_db`` attribute on the manager (a string
|
|
|
|
containing the name of the database to use).
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
For example, if you want to return a custom ``QuerySet`` class from
|
2013-03-08 14:15:23 +00:00
|
|
|
the ``get_queryset`` method, you could do this::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
class MyManager(models.Manager):
|
2013-03-08 14:15:23 +00:00
|
|
|
def get_queryset(self):
|
2009-12-22 15:18:51 +00:00
|
|
|
qs = CustomQuerySet(self.model)
|
|
|
|
if self._db is not None:
|
|
|
|
qs = qs.using(self._db)
|
|
|
|
return qs
|
|
|
|
|
|
|
|
Exposing multiple databases in Django's admin interface
|
|
|
|
=======================================================
|
|
|
|
|
|
|
|
Django's admin doesn't have any explicit support for multiple
|
|
|
|
databases. If you want to provide an admin interface for a model on a
|
2011-03-29 10:24:42 +00:00
|
|
|
database other than that specified by your router chain, you'll
|
2010-01-22 14:30:06 +00:00
|
|
|
need to write custom :class:`~django.contrib.admin.ModelAdmin` classes
|
|
|
|
that will direct the admin to use a specific database for content.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-11-21 19:00:40 +00:00
|
|
|
``ModelAdmin`` objects have five methods that require customization for
|
2010-01-09 17:09:20 +00:00
|
|
|
multiple-database support::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
class MultiDBModelAdmin(admin.ModelAdmin):
|
2010-01-09 17:09:20 +00:00
|
|
|
# A handy constant for the name of the alternate database.
|
2009-12-22 15:18:51 +00:00
|
|
|
using = 'other'
|
|
|
|
|
|
|
|
def save_model(self, request, obj, form, change):
|
2010-01-09 17:09:20 +00:00
|
|
|
# Tell Django to save objects to the 'other' database.
|
2009-12-22 15:18:51 +00:00
|
|
|
obj.save(using=self.using)
|
|
|
|
|
2011-03-03 00:24:41 +00:00
|
|
|
def delete_model(self, request, obj):
|
2010-11-21 19:00:40 +00:00
|
|
|
# Tell Django to delete objects from the 'other' database
|
|
|
|
obj.delete(using=self.using)
|
|
|
|
|
2013-03-08 14:15:23 +00:00
|
|
|
def get_queryset(self, request):
|
2010-01-09 17:09:20 +00:00
|
|
|
# Tell Django to look for objects on the 'other' database.
|
2017-01-22 06:57:14 +00:00
|
|
|
return super().get_queryset(request).using(self.using)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2015-12-24 15:25:59 +00:00
|
|
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
2009-12-22 15:18:51 +00:00
|
|
|
# Tell Django to populate ForeignKey widgets using a query
|
2010-01-09 17:09:20 +00:00
|
|
|
# on the 'other' database.
|
2017-01-22 06:57:14 +00:00
|
|
|
return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2015-12-24 15:25:59 +00:00
|
|
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
2009-12-22 15:18:51 +00:00
|
|
|
# Tell Django to populate ManyToMany widgets using a query
|
2010-01-09 17:09:20 +00:00
|
|
|
# on the 'other' database.
|
2017-01-22 06:57:14 +00:00
|
|
|
return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
The implementation provided here implements a multi-database strategy
|
|
|
|
where all objects of a given type are stored on a specific database
|
|
|
|
(e.g., all ``User`` objects are in the ``other`` database). If your
|
|
|
|
usage of multiple databases is more complex, your ``ModelAdmin`` will
|
|
|
|
need to reflect that strategy.
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2016-08-02 23:55:57 +00:00
|
|
|
:class:`~django.contrib.admin.InlineModelAdmin` objects can be handled in a
|
|
|
|
similar fashion. They require three customized methods::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
class MultiDBTabularInline(admin.TabularInline):
|
|
|
|
using = 'other'
|
|
|
|
|
2013-03-08 14:15:23 +00:00
|
|
|
def get_queryset(self, request):
|
2010-01-09 17:09:20 +00:00
|
|
|
# Tell Django to look for inline objects on the 'other' database.
|
2017-01-22 06:57:14 +00:00
|
|
|
return super().get_queryset(request).using(self.using)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2015-12-24 15:25:59 +00:00
|
|
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
2009-12-22 15:18:51 +00:00
|
|
|
# Tell Django to populate ForeignKey widgets using a query
|
2010-01-09 17:09:20 +00:00
|
|
|
# on the 'other' database.
|
2017-01-22 06:57:14 +00:00
|
|
|
return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2015-12-24 15:25:59 +00:00
|
|
|
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
2009-12-22 15:18:51 +00:00
|
|
|
# Tell Django to populate ManyToMany widgets using a query
|
2010-01-09 17:09:20 +00:00
|
|
|
# on the 'other' database.
|
2017-01-22 06:57:14 +00:00
|
|
|
return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)
|
2009-12-22 15:18:51 +00:00
|
|
|
|
2010-01-22 14:30:06 +00:00
|
|
|
Once you've written your model admin definitions, they can be
|
|
|
|
registered with any ``Admin`` instance::
|
2009-12-22 15:18:51 +00:00
|
|
|
|
|
|
|
from django.contrib import admin
|
|
|
|
|
2010-01-09 17:09:20 +00:00
|
|
|
# Specialize the multi-db admin objects for use with specific models.
|
2009-12-22 15:18:51 +00:00
|
|
|
class BookInline(MultiDBTabularInline):
|
|
|
|
model = Book
|
|
|
|
|
|
|
|
class PublisherAdmin(MultiDBModelAdmin):
|
|
|
|
inlines = [BookInline]
|
|
|
|
|
|
|
|
admin.site.register(Author, MultiDBModelAdmin)
|
|
|
|
admin.site.register(Publisher, PublisherAdmin)
|
|
|
|
|
2012-08-30 10:45:11 +00:00
|
|
|
othersite = admin.AdminSite('othersite')
|
2009-12-22 15:18:51 +00:00
|
|
|
othersite.register(Publisher, MultiDBModelAdmin)
|
|
|
|
|
|
|
|
This example sets up two admin sites. On the first site, the
|
|
|
|
``Author`` and ``Publisher`` objects are exposed; ``Publisher``
|
2017-10-31 01:47:09 +00:00
|
|
|
objects have a tabular inline showing books published by that
|
2009-12-22 15:18:51 +00:00
|
|
|
publisher. The second site exposes just publishers, without the
|
|
|
|
inlines.
|
2010-03-08 03:19:26 +00:00
|
|
|
|
|
|
|
Using raw cursors with multiple databases
|
|
|
|
=========================================
|
|
|
|
|
|
|
|
If you are using more than one database you can use
|
|
|
|
``django.db.connections`` to obtain the connection (and cursor) for a
|
|
|
|
specific database. ``django.db.connections`` is a dictionary-like
|
2010-12-16 22:37:29 +00:00
|
|
|
object that allows you to retrieve a specific connection using its
|
2010-03-08 03:19:26 +00:00
|
|
|
alias::
|
|
|
|
|
|
|
|
from django.db import connections
|
2017-11-28 13:12:28 +00:00
|
|
|
with connections['my_db_alias'].cursor() as cursor:
|
|
|
|
...
|
2010-05-09 07:44:06 +00:00
|
|
|
|
|
|
|
Limitations of multiple databases
|
|
|
|
=================================
|
|
|
|
|
|
|
|
.. _no_cross_database_relations:
|
|
|
|
|
|
|
|
Cross-database relations
|
|
|
|
------------------------
|
|
|
|
|
|
|
|
Django doesn't currently provide any support for foreign key or
|
|
|
|
many-to-many relationships spanning multiple databases. If you
|
|
|
|
have used a router to partition models to different databases,
|
|
|
|
any foreign key and many-to-many relationships defined by those
|
|
|
|
models must be internal to a single database.
|
|
|
|
|
|
|
|
This is because of referential integrity. In order to maintain a
|
|
|
|
relationship between two objects, Django needs to know that the
|
|
|
|
primary key of the related object is valid. If the primary key is
|
|
|
|
stored on a separate database, it's not possible to easily evaluate
|
|
|
|
the validity of a primary key.
|
|
|
|
|
|
|
|
If you're using Postgres, Oracle, or MySQL with InnoDB, this is
|
|
|
|
enforced at the database integrity level -- database level key
|
|
|
|
constraints prevent the creation of relations that can't be validated.
|
|
|
|
|
|
|
|
However, if you're using SQLite or MySQL with MyISAM tables, there is
|
|
|
|
no enforced referential integrity; as a result, you may be able to
|
|
|
|
'fake' cross database foreign keys. However, this configuration is not
|
|
|
|
officially supported by Django.
|
2012-11-22 19:09:40 +00:00
|
|
|
|
|
|
|
.. _contrib_app_multiple_databases:
|
|
|
|
|
|
|
|
Behavior of contrib apps
|
|
|
|
------------------------
|
|
|
|
|
|
|
|
Several contrib apps include models, and some apps depend on others. Since
|
|
|
|
cross-database relationships are impossible, this creates some restrictions on
|
|
|
|
how you can split these models across databases:
|
|
|
|
|
|
|
|
- each one of ``contenttypes.ContentType``, ``sessions.Session`` and
|
|
|
|
``sites.Site`` can be stored in any database, given a suitable router.
|
|
|
|
- ``auth`` models — ``User``, ``Group`` and ``Permission`` — are linked
|
|
|
|
together and linked to ``ContentType``, so they must be stored in the same
|
|
|
|
database as ``ContentType``.
|
2016-09-01 13:51:05 +00:00
|
|
|
- ``admin`` depends on ``auth``, so its models must be in the same database
|
2014-05-13 11:24:28 +00:00
|
|
|
as ``auth``.
|
2012-11-22 19:09:40 +00:00
|
|
|
- ``flatpages`` and ``redirects`` depend on ``sites``, so their models must be
|
|
|
|
in the same database as ``sites``.
|
|
|
|
|
|
|
|
In addition, some objects are automatically created just after
|
2013-11-21 14:04:31 +00:00
|
|
|
:djadmin:`migrate` creates a table to hold them in a database:
|
2012-11-22 19:09:40 +00:00
|
|
|
|
|
|
|
- a default ``Site``,
|
|
|
|
- a ``ContentType`` for each model (including those not stored in that
|
|
|
|
database),
|
2019-02-25 19:56:36 +00:00
|
|
|
- the ``Permission``\s for each model (including those not stored in that
|
2012-11-22 19:09:40 +00:00
|
|
|
database).
|
|
|
|
|
|
|
|
For common setups with multiple databases, it isn't useful to have these
|
2014-05-20 19:54:56 +00:00
|
|
|
objects in more than one database. Common setups include primary/replica and
|
2014-08-26 19:43:23 +00:00
|
|
|
connecting to external databases. Therefore, it's recommended to write a
|
|
|
|
:ref:`database router<topics-db-multi-db-routing>` that allows synchronizing
|
|
|
|
these three models to only one database. Use the same approach for contrib
|
|
|
|
and third-party apps that don't need their tables in multiple databases.
|
2012-11-22 19:09:40 +00:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
2014-04-10 23:32:20 +00:00
|
|
|
If you're synchronizing content types to more than one database, be aware
|
2012-11-22 19:09:40 +00:00
|
|
|
that their primary keys may not match across databases. This may result in
|
|
|
|
data corruption or data loss.
|