multi-db.txt 30 KB

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