multi-db.txt 29 KB

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