multi-db.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. .. _topics-db-multi-db:
  2. ==================
  3. Multiple databases
  4. ==================
  5. .. versionadded:: 1.2
  6. This topic guide describes Django's support for interacting with
  7. multiple databases. Most of the rest of Django's documentation assumes
  8. you are interacting with a single database. If you want to interact
  9. with multiple databases, you'll need to take some additional steps.
  10. Defining your databases
  11. =======================
  12. The first step to using more than one database with Django is to tell
  13. Django about the database servers you'll be using. This is done using
  14. the :setting:`DATABASES` setting. This setting maps database aliases,
  15. which are a way to refer to a specific database throughout Django, to
  16. a dictionary of settings for that specific connection. The settings in
  17. the inner dictionaries are described fully in the :setting:`DATABASES`
  18. documentation.
  19. Databases can have any alias you choose. However, the alias
  20. ``default`` has special significance. Django uses the database with
  21. the alias of ``default`` when no other database has been selected. If
  22. you don't have a ``default`` database, you need to be careful to
  23. always specify the database that you want to use.
  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 omit one or
  113. more of them. If one of the methods is omitted, Django will skip that
  114. 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. The approach of splitting ``contrib.auth`` onto a different
  149. database won't actually work on Postgres, Oracle, or MySQL with
  150. InnoDB tables. ForeignKeys to a remote database won't work due as
  151. they introduce referential integrity problems. If you're using
  152. SQLite or MySQL with MyISAM tables, there is no referential
  153. integrity checking, so you will be able to define cross-database
  154. foreign keys.
  155. The master/slave configuration described is also flawed -- it
  156. doesn't provide any solution for handling replication lag (i.e.,
  157. query inconsistencies introduced because of the time taken for a
  158. write to propagate to the slaves). It also doesn't consider the
  159. interaction of transactions with the database utilization strategy.
  160. So - what does this mean in practice? Say you want ``contrib.auth`` to
  161. exist on the 'credentials' database, and you want all other models in a
  162. master/slave relationship between the databases 'master', 'slave1' and
  163. 'slave2'. To implement this, you would need 2 routers::
  164. class AuthRouter(object):
  165. """A router to control all database operations on models in
  166. the contrib.auth application"""
  167. def db_for_read(self, model, **hints):
  168. "Point all operations on auth models to 'credentials'"
  169. if model._meta.app_label == 'auth':
  170. return 'credentials'
  171. return None
  172. def db_for_write(self, model, **hints):
  173. "Point all operations on auth models to 'credentials'"
  174. if model._meta.app_label == 'auth':
  175. return 'credentials'
  176. return None
  177. def allow_relation(self, obj1, obj2, **hints):
  178. "Allow any relation if a model in Auth is involved"
  179. if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth':
  180. return True
  181. return None
  182. def allow_syncdb(self, db, model):
  183. "Make sure the auth app only appears on the 'credentials' db"
  184. if db == 'credentials':
  185. return model._meta.app_label == 'auth'
  186. elif model._meta.app_label == 'auth':
  187. return False
  188. return None
  189. class MasterSlaveRouter(object):
  190. """A router that sets up a simple master/slave configuration"""
  191. def db_for_read(self, model, **hints):
  192. "Point all read operations to a random slave"
  193. return random.choice(['slave1','slave2'])
  194. def db_for_write(self, model, **hints):
  195. "Point all write operations to the master"
  196. return 'master'
  197. def allow_relation(self, obj1, obj2, **hints):
  198. "Allow any relation between two objects in the db pool"
  199. db_list = ('master','slave1','slave2')
  200. if obj1 in db_list and obj2 in db_list:
  201. return True
  202. return None
  203. def allow_syncdb(self, db, model):
  204. "Explicitly put all models on all databases."
  205. return True
  206. Then, in your settings file, add the following (substituting ``path.to.`` with
  207. the actual python path to the module where you define the routers)::
  208. DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.MasterSlaveRouter']
  209. The order in which routers are processed is significant. Routers will
  210. be queried in the order the are listed in the
  211. :setting:`DATABASE_ROUTERS` setting . In this example, the
  212. ``AuthRouter`` is processed before the ``MasterSlaveRouter``, and as a
  213. result, decisions concerning the models in ``auth`` are processed
  214. before any other decision is made. If the :setting:`DATABASE_ROUTERS`
  215. setting listed the two routers in the other order,
  216. ``MasterSlaveRouter.allow_syncdb()`` would be processed first. The
  217. catch-all nature of the MasterSlaveRouter implementation would mean
  218. that all models would be available on all databases.
  219. With this setup installed, lets run some Django code::
  220. >>> # This retrieval will be performed on the 'credentials' database
  221. >>> fred = User.objects.get(username='fred')
  222. >>> fred.first_name = 'Frederick'
  223. >>> # This save will also be directed to 'credentials'
  224. >>> fred.save()
  225. >>> # These retrieval will be randomly allocated to a slave database
  226. >>> dna = Person.objects.get(name='Douglas Adams')
  227. >>> # A new object has no database allocation when created
  228. >>> mh = Book(title='Mostly Harmless')
  229. >>> # This assignment will consult the router, and set mh onto
  230. >>> # the same database as the author object
  231. >>> mh.author = dna
  232. >>> # This save will force the 'mh' instance onto the master database...
  233. >>> mh.save()
  234. >>> # ... but if we re-retrieve the object, it will come back on a slave
  235. >>> mh = Book.objects.get(title='Mostly Harmless')
  236. Manually selecting a database
  237. =============================
  238. Django also provides an API that allows you to maintain complete control
  239. over database usage in your code. A manually specified database allocation
  240. will take priority over a database allocated by a router.
  241. Manually selecting a database for a ``QuerySet``
  242. ------------------------------------------------
  243. You can select the database for a ``QuerySet`` at any point in the
  244. ``QuerySet`` "chain." Just call ``using()`` on the ``QuerySet`` to get
  245. another ``QuerySet`` that uses the specified database.
  246. ``using()`` takes a single argument: the alias of the database on
  247. which you want to run the query. For example::
  248. >>> # This will run on the 'default' database.
  249. >>> Author.objects.all()
  250. >>> # So will this.
  251. >>> Author.objects.using('default').all()
  252. >>> # This will run on the 'other' database.
  253. >>> Author.objects.using('other').all()
  254. Selecting a database for ``save()``
  255. -----------------------------------
  256. Use the ``using`` keyword to ``Model.save()`` to specify to which
  257. database the data should be saved.
  258. For example, to save an object to the ``legacy_users`` database, you'd
  259. use this::
  260. >>> my_object.save(using='legacy_users')
  261. If you don't specify ``using``, the ``save()`` method will save into
  262. the default database allocated by the routers.
  263. Moving an object from one database to another
  264. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  265. If you've saved an instance to one database, it might be tempting to
  266. use ``save(using=...)`` as a way to migrate the instance to a new
  267. database. However, if you don't take appropriate steps, this could
  268. have some unexpected consequences.
  269. Consider the following example::
  270. >>> p = Person(name='Fred')
  271. >>> p.save(using='first') # (statement 1)
  272. >>> p.save(using='second') # (statement 2)
  273. In statement 1, a new ``Person`` object is saved to the ``first``
  274. database. At this time, ``p`` doesn't have a primary key, so Django
  275. issues a SQL ``INSERT`` statement. This creates a primary key, and
  276. Django assigns that primary key to ``p``.
  277. When the save occurs in statement 2, ``p`` already has a primary key
  278. value, and Django will attempt to use that primary key on the new
  279. database. If the primary key value isn't in use in the ``second``
  280. database, then you won't have any problems -- the object will be
  281. copied to the new database.
  282. However, if the primary key of ``p`` is already in use on the
  283. ``second`` database, the existing object in the ``second`` database
  284. will be overridden when ``p`` is saved.
  285. You can avoid this in two ways. First, you can clear the primary key
  286. of the instance. If an object has no primary key, Django will treat it
  287. as a new object, avoiding any loss of data on the ``second``
  288. database::
  289. >>> p = Person(name='Fred')
  290. >>> p.save(using='first')
  291. >>> p.pk = None # Clear the primary key.
  292. >>> p.save(using='second') # Write a completely new object.
  293. The second option is to use the ``force_insert`` option to ``save()``
  294. to ensure that Django does a SQL ``INSERT``::
  295. >>> p = Person(name='Fred')
  296. >>> p.save(using='first')
  297. >>> p.save(using='second', force_insert=True)
  298. This will ensure that the person named ``Fred`` will have the same
  299. primary key on both databases. If that primary key is already in use
  300. when you try to save onto the ``second`` database, an error will be
  301. raised.
  302. Selecting a database to delete from
  303. -----------------------------------
  304. By default, a call to delete an existing object will be executed on
  305. the same database that was used to retrieve the object in the first
  306. place::
  307. >>> u = User.objects.using('legacy_users').get(username='fred')
  308. >>> u.delete() # will delete from the `legacy_users` database
  309. To specify the database from which a model will be deleted, pass a
  310. ``using`` keyword argument to the ``Model.delete()`` method. This
  311. argument works just like the ``using`` keyword argument to ``save()``.
  312. For example, if you're migrating a user from the ``legacy_users``
  313. database to the ``new_users`` database, you might use these commands::
  314. >>> user_obj.save(using='new_users')
  315. >>> user_obj.delete(using='legacy_users')
  316. Using managers with multiple databases
  317. --------------------------------------
  318. Use the ``db_manager()`` method on managers to give managers access to
  319. a non-default database.
  320. For example, say you have a custom manager method that touches the
  321. database -- ``User.objects.create_user()``. Because ``create_user()``
  322. is a manager method, not a ``QuerySet`` method, you can't do
  323. ``User.objects.using('new_users').create_user()``. (The
  324. ``create_user()`` method is only available on ``User.objects``, the
  325. manager, not on ``QuerySet`` objects derived from the manager.) The
  326. solution is to use ``db_manager()``, like this::
  327. User.objects.db_manager('new_users').create_user(...)
  328. ``db_manager()`` returns a copy of the manager bound to the database you specify.
  329. Using ``get_query_set()`` with multiple databases
  330. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  331. If you're overriding ``get_query_set()`` on your manager, be sure to
  332. either call the method on the parent (using ``super()``) or do the
  333. appropriate handling of the ``_db`` attribute on the manager (a string
  334. containing the name of the database to use).
  335. For example, if you want to return a custom ``QuerySet`` class from
  336. the ``get_query_set`` method, you could do this::
  337. class MyManager(models.Manager):
  338. def get_query_set(self):
  339. qs = CustomQuerySet(self.model)
  340. if self._db is not None:
  341. qs = qs.using(self._db)
  342. return qs
  343. Exposing multiple databases in Django's admin interface
  344. =======================================================
  345. Django's admin doesn't have any explicit support for multiple
  346. databases. If you want to provide an admin interface for a model on a
  347. database other than that that specified by your router chain, you'll
  348. need to write custom :class:`~django.contrib.admin.ModelAdmin` classes
  349. that will direct the admin to use a specific database for content.
  350. ``ModelAdmin`` objects have four methods that require customization for
  351. multiple-database support::
  352. class MultiDBModelAdmin(admin.ModelAdmin):
  353. # A handy constant for the name of the alternate database.
  354. using = 'other'
  355. def save_model(self, request, obj, form, change):
  356. # Tell Django to save objects to the 'other' database.
  357. obj.save(using=self.using)
  358. def queryset(self, request):
  359. # Tell Django to look for objects on the 'other' database.
  360. return super(MultiDBModelAdmin, self).queryset(request).using(self.using)
  361. def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
  362. # Tell Django to populate ForeignKey widgets using a query
  363. # on the 'other' database.
  364. return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
  365. def formfield_for_manytomany(self, db_field, request=None, **kwargs):
  366. # Tell Django to populate ManyToMany widgets using a query
  367. # on the 'other' database.
  368. return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
  369. The implementation provided here implements a multi-database strategy
  370. where all objects of a given type are stored on a specific database
  371. (e.g., all ``User`` objects are in the ``other`` database). If your
  372. usage of multiple databases is more complex, your ``ModelAdmin`` will
  373. need to reflect that strategy.
  374. Inlines can be handled in a similar fashion. They require three customized methods::
  375. class MultiDBTabularInline(admin.TabularInline):
  376. using = 'other'
  377. def queryset(self, request):
  378. # Tell Django to look for inline objects on the 'other' database.
  379. return super(MultiDBTabularInline, self).queryset(request).using(self.using)
  380. def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
  381. # Tell Django to populate ForeignKey widgets using a query
  382. # on the 'other' database.
  383. return super(MultiDBTabularInline, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
  384. def formfield_for_manytomany(self, db_field, request=None, **kwargs):
  385. # Tell Django to populate ManyToMany widgets using a query
  386. # on the 'other' database.
  387. return super(MultiDBTabularInline, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
  388. Once you've written your model admin definitions, they can be
  389. registered with any ``Admin`` instance::
  390. from django.contrib import admin
  391. # Specialize the multi-db admin objects for use with specific models.
  392. class BookInline(MultiDBTabularInline):
  393. model = Book
  394. class PublisherAdmin(MultiDBModelAdmin):
  395. inlines = [BookInline]
  396. admin.site.register(Author, MultiDBModelAdmin)
  397. admin.site.register(Publisher, PublisherAdmin)
  398. othersite = admin.Site('othersite')
  399. othersite.register(Publisher, MultiDBModelAdmin)
  400. This example sets up two admin sites. On the first site, the
  401. ``Author`` and ``Publisher`` objects are exposed; ``Publisher``
  402. objects have an tabular inline showing books published by that
  403. publisher. The second site exposes just publishers, without the
  404. inlines.