multi-db.txt 27 KB

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