multi-db.txt 26 KB

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