multi-db.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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). However, you
  75. can implement more interesting behaviors by defining a different
  76. routing scheme.
  77. Database routers
  78. ----------------
  79. A database Router is a class that provides four methods:
  80. .. method:: db_for_read(model, **hints)
  81. Suggest the database that should be used for read operations for
  82. objects of type ``model``.
  83. If a database operation is able to provide any additional
  84. information that might assist in selecting a database, it will be
  85. provided in the ``hints`` dictionary. Details on valid hints are
  86. provided :ref:`below <topics-db-multi-db-hints>`.
  87. Returns None if there is no suggestion.
  88. .. method:: db_for_write(model, **hints)
  89. Suggest the database that should be used for writes of objects of
  90. type Model.
  91. If a database operation is able to provide any additional
  92. information that might assist in selecting a database, it will be
  93. provided in the ``hints`` dictionary. Details on valid hints are
  94. provided :ref:`below <topics-db-multi-db-hints>`.
  95. Returns None if there is no suggestion.
  96. .. method:: allow_relation(obj1, obj2, **hints)
  97. Return True if a relation between obj1 and obj2 should be
  98. allowed, False if the relation should be prevented, or None if
  99. the router has no opinion. This is purely a validation operation,
  100. used by foreign key and many to many operations to determine if a
  101. relation should be allowed between two objects.
  102. .. method:: allow_syncdb(db, model)
  103. Determine if the ``model`` should be synchronized onto the
  104. database with alias ``db``. Return True if the model should be
  105. synchronized, False if it should not be synchronized, or None if
  106. the router has no opinion. This method can be used to determine
  107. the availability of a model on a given database.
  108. .. _topics-db-multi-db-hints:
  109. Hints
  110. ~~~~~
  111. The hints received by the database router can be used to decide which
  112. database should receive a given request.
  113. At present, the only hint that will be provided is ``instance``, an
  114. object instance that is related to the read or write operation that is
  115. underway. This might be the instance that is being saved, or it might
  116. be an instance that is being added in a many-to-many relation. In some
  117. cases, no instance hint will be provided at all. The router checks for
  118. the existence of an instance hint, and determine if that hint should be
  119. used to alter routing behavior.
  120. Using routers
  121. -------------
  122. Database routers are installed using the :setting:`DATABASE_ROUTERS`
  123. setting. This setting defines a list of class names, each specifying a
  124. router that should be used by the master router
  125. (``django.db.router``).
  126. The master router is used by Django's database operations to allocate
  127. database usage. Whenever a query needs to know which database to use,
  128. it calls the master router, providing a model and a hint (if
  129. available). Django then tries each router in turn until a database
  130. suggestion can be found. If no suggestion can be found, it tries the
  131. current ``_state.db`` of the hint instance. If a hint instance wasn't
  132. provided, or the instance doesn't currently have database state, the
  133. master router will allocate the ``default`` database.
  134. An example
  135. ----------
  136. .. admonition:: Example purposes only!
  137. This example is intended as a demonstration of how the router
  138. infrastructure can be used to alter database usage. It
  139. intentionally ignores some complex issues in order to
  140. demonstrate how routers are used.
  141. The approach of splitting ``contrib.auth`` onto a different
  142. database won't actually work on Postgres, Oracle, or MySQL with
  143. InnoDB tables. ForeignKeys to a remote database won't work due as
  144. they introduce referential integrity problems. If you're using
  145. SQLite or MySQL with MyISAM tables, there is no referential
  146. integrity checking, so you will be able to define cross-database
  147. foreign keys.
  148. The master/slave configuration described is also flawed -- it
  149. doesn't provide any solution for handling replication lag (i.e.,
  150. query inconsistencies introduced because of the time taken for a
  151. write to propagate to the slaves). It also doesn't consider the
  152. interaction of transactions with the database utilization strategy.
  153. So - what does this mean in practice? Say you want ``contrib.auth`` to
  154. exist on the 'credentials' database, and you want all other models in a
  155. master/slave relationship between the databases 'master', 'slave1' and
  156. 'slave2'. To implement this, you would need 2 routers::
  157. class AuthRouter(object):
  158. """A router to control all database operations on models in
  159. the contrib.auth application"""
  160. def db_for_read(self, model, **hints):
  161. "Point all operations on auth models to 'credentials'"
  162. if model._meta.app_label == 'auth':
  163. return 'credentials'
  164. return None
  165. def db_for_write(self, model, **hints):
  166. "Point all operations on auth models to 'credentials'"
  167. if model._meta.app_label == 'auth':
  168. return 'credentials'
  169. return None
  170. def allow_relation(self, obj1, obj2, **hints):
  171. "Allow any relation if a model in Auth is involved"
  172. if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth':
  173. return True
  174. return None
  175. def allow_syncdb(self, db, model):
  176. "Make sure the auth app only appears on the 'credentials' db"
  177. if db == 'credentials':
  178. return model._meta.app_label == 'auth'
  179. elif model._meta.app_label == 'auth':
  180. return False
  181. return None
  182. class MasterSlaveRouter(object):
  183. """A router that sets up a simple master/slave configuration"""
  184. def db_for_read(self, model, **hints):
  185. "Point all read operations to a random slave"
  186. return random.choice(['slave1','slave2'])
  187. def db_for_write(self, model, **hints):
  188. "Point all write operations to the master"
  189. return 'master'
  190. def allow_relation(self, obj1, obj2, **hints):
  191. "Allow any relation between two objects in the db pool"
  192. db_list = ('master','slave1','slave2')
  193. if obj1 in db_list and obj2 in db_list:
  194. return True
  195. return None
  196. def allow_syncdb(self, db, model):
  197. "Explicitly put all models on all databases."
  198. return True
  199. Then, in your settings file, add the following (substituting ``path.to.`` with
  200. the actual python path to the module where you define the routers)::
  201. DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.MasterSlaveRouter']
  202. The order in which routers are processed is significant. Routers will
  203. be queried in the order the are listed in the
  204. :setting:`DATABASE_ROUTERS` setting . In this example, the
  205. ``AuthRouter`` is processed before the ``MasterSlaveRouter``, and as a
  206. result, decisions concerning the models in ``auth`` are processed
  207. before any other decision is made. If the :setting:`DATABASE_ROUTERS`
  208. setting listed the two routers in the other order,
  209. ``MasterSlaveRouter.allow_syncdb()`` would be processed first. The
  210. catch-all nature of the MasterSlaveRouter implementation would mean
  211. that all models would be available on all databases.
  212. With this setup installed, lets run some Django code::
  213. >>> # This retrieval will be performed on the 'credentials' database
  214. >>> fred = User.objects.get(username='fred')
  215. >>> fred.first_name = 'Frederick'
  216. >>> # This save will also be directed to 'credentials'
  217. >>> fred.save()
  218. >>> # These retrieval will be randomly allocated to a slave database
  219. >>> dna = Person.objects.get(name='Douglas Adams')
  220. >>> # A new object has no database allocation when created
  221. >>> mh = Book(title='Mostly Harmless')
  222. >>> # This assignment will consult the router, and set mh onto
  223. >>> # the same database as the author object
  224. >>> mh.author = dna
  225. >>> # This save will force the 'mh' instance onto the master database...
  226. >>> mh.save()
  227. >>> # ... but if we re-retrieve the object, it will come back on a slave
  228. >>> mh = Book.objects.get(title='Mostly Harmless')
  229. Manually selecting a database
  230. =============================
  231. Django also provides an API that allows you to maintain complete control
  232. over database usage in your code. A manually specified database allocation
  233. will take priority over a database allocated by a router.
  234. Manually selecting a database for a ``QuerySet``
  235. ------------------------------------------------
  236. You can select the database for a ``QuerySet`` at any point in the
  237. ``QuerySet`` "chain." Just call ``using()`` on the ``QuerySet`` to get
  238. another ``QuerySet`` that uses the specified database.
  239. ``using()`` takes a single argument: the alias of the database on
  240. which you want to run the query. For example::
  241. >>> # This will run on the 'default' database.
  242. >>> Author.objects.all()
  243. >>> # So will this.
  244. >>> Author.objects.using('default').all()
  245. >>> # This will run on the 'other' database.
  246. >>> Author.objects.using('other').all()
  247. Selecting a database for ``save()``
  248. -----------------------------------
  249. Use the ``using`` keyword to ``Model.save()`` to specify to which
  250. database the data should be saved.
  251. For example, to save an object to the ``legacy_users`` database, you'd
  252. use this::
  253. >>> my_object.save(using='legacy_users')
  254. If you don't specify ``using``, the ``save()`` method will save into
  255. the default database allocated by the routers.
  256. Moving an object from one database to another
  257. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  258. If you've saved an instance to one database, it might be tempting to
  259. use ``save(using=...)`` as a way to migrate the instance to a new
  260. database. However, if you don't take appropriate steps, this could
  261. have some unexpected consequences.
  262. Consider the following example::
  263. >>> p = Person(name='Fred')
  264. >>> p.save(using='first') # (statement 1)
  265. >>> p.save(using='second') # (statement 2)
  266. In statement 1, a new ``Person`` object is saved to the ``first``
  267. database. At this time, ``p`` doesn't have a primary key, so Django
  268. issues a SQL ``INSERT`` statement. This creates a primary key, and
  269. Django assigns that primary key to ``p``.
  270. When the save occurs in statement 2, ``p`` already has a primary key
  271. value, and Django will attempt to use that primary key on the new
  272. database. If the primary key value isn't in use in the ``second``
  273. database, then you won't have any problems -- the object will be
  274. copied to the new database.
  275. However, if the primary key of ``p`` is already in use on the
  276. ``second`` database, the existing object in the ``second`` database
  277. will be overridden when ``p`` is saved.
  278. You can avoid this in two ways. First, you can clear the primary key
  279. of the instance. If an object has no primary key, Django will treat it
  280. as a new object, avoiding any loss of data on the ``second``
  281. database::
  282. >>> p = Person(name='Fred')
  283. >>> p.save(using='first')
  284. >>> p.pk = None # Clear the primary key.
  285. >>> p.save(using='second') # Write a completely new object.
  286. The second option is to use the ``force_insert`` option to ``save()``
  287. to ensure that Django does a SQL ``INSERT``::
  288. >>> p = Person(name='Fred')
  289. >>> p.save(using='first')
  290. >>> p.save(using='second', force_insert=True)
  291. This will ensure that the person named ``Fred`` will have the same
  292. primary key on both databases. If that primary key is already in use
  293. when you try to save onto the ``second`` database, an error will be
  294. raised.
  295. Selecting a database to delete from
  296. -----------------------------------
  297. By default, a call to delete an existing object will be executed on
  298. the same database that was used to retrieve the object in the first
  299. place::
  300. >>> u = User.objects.using('legacy_users').get(username='fred')
  301. >>> u.delete() # will delete from the `legacy_users` database
  302. To specify the database from which a model will be deleted, pass a
  303. ``using`` keyword argument to the ``Model.delete()`` method. This
  304. argument works just like the ``using`` keyword argument to ``save()``.
  305. For example, if you're migrating a user from the ``legacy_users``
  306. database to the ``new_users`` database, you might use these commands::
  307. >>> user_obj.save(using='new_users')
  308. >>> user_obj.delete(using='legacy_users')
  309. Using managers with multiple databases
  310. --------------------------------------
  311. Use the ``db_manager()`` method on managers to give managers access to
  312. a non-default database.
  313. For example, say you have a custom manager method that touches the
  314. database -- ``User.objects.create_user()``. Because ``create_user()``
  315. is a manager method, not a ``QuerySet`` method, you can't do
  316. ``User.objects.using('new_users').create_user()``. (The
  317. ``create_user()`` method is only available on ``User.objects``, the
  318. manager, not on ``QuerySet`` objects derived from the manager.) The
  319. solution is to use ``db_manager()``, like this::
  320. User.objects.db_manager('new_users').create_user(...)
  321. ``db_manager()`` returns a copy of the manager bound to the database you specify.
  322. Using ``get_query_set()`` with multiple databases
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  324. If you're overriding ``get_query_set()`` on your manager, be sure to
  325. either call the method on the parent (using ``super()``) or do the
  326. appropriate handling of the ``_db`` attribute on the manager (a string
  327. containing the name of the database to use).
  328. For example, if you want to return a custom ``QuerySet`` class from
  329. the ``get_query_set`` method, you could do this::
  330. class MyManager(models.Manager):
  331. def get_query_set(self):
  332. qs = CustomQuerySet(self.model)
  333. if self._db is not None:
  334. qs = qs.using(self._db)
  335. return qs
  336. Exposing multiple databases in Django's admin interface
  337. =======================================================
  338. Django's admin doesn't have any explicit support for multiple
  339. databases. If you want to provide an admin interface for a model on a
  340. database other than that that specified by your router chain, you'll
  341. need to write custom :class:`~django.contrib.admin.ModelAdmin` classes
  342. that will direct the admin to use a specific database for content.
  343. ``ModelAdmin`` objects have four methods that require customization for
  344. multiple-database support::
  345. class MultiDBModelAdmin(admin.ModelAdmin):
  346. # A handy constant for the name of the alternate database.
  347. using = 'other'
  348. def save_model(self, request, obj, form, change):
  349. # Tell Django to save objects to the 'other' database.
  350. obj.save(using=self.using)
  351. def queryset(self, request):
  352. # Tell Django to look for objects on the 'other' database.
  353. return super(MultiDBModelAdmin, self).queryset(request).using(self.using)
  354. def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
  355. # Tell Django to populate ForeignKey widgets using a query
  356. # on the 'other' database.
  357. return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
  358. def formfield_for_manytomany(self, db_field, request=None, **kwargs):
  359. # Tell Django to populate ManyToMany widgets using a query
  360. # on the 'other' database.
  361. return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
  362. The implementation provided here implements a multi-database strategy
  363. where all objects of a given type are stored on a specific database
  364. (e.g., all ``User`` objects are in the ``other`` database). If your
  365. usage of multiple databases is more complex, your ``ModelAdmin`` will
  366. need to reflect that strategy.
  367. Inlines can be handled in a similar fashion. They require three customized methods::
  368. class MultiDBTabularInline(admin.TabularInline):
  369. using = 'other'
  370. def queryset(self, request):
  371. # Tell Django to look for inline objects on the 'other' database.
  372. return super(MultiDBTabularInline, self).queryset(request).using(self.using)
  373. def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
  374. # Tell Django to populate ForeignKey widgets using a query
  375. # on the 'other' database.
  376. return super(MultiDBTabularInline, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs)
  377. def formfield_for_manytomany(self, db_field, request=None, **kwargs):
  378. # Tell Django to populate ManyToMany widgets using a query
  379. # on the 'other' database.
  380. return super(MultiDBTabularInline, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs)
  381. Once you've written your model admin definitions, they can be
  382. registered with any ``Admin`` instance::
  383. from django.contrib import admin
  384. # Specialize the multi-db admin objects for use with specific models.
  385. class BookInline(MultiDBTabularInline):
  386. model = Book
  387. class PublisherAdmin(MultiDBModelAdmin):
  388. inlines = [BookInline]
  389. admin.site.register(Author, MultiDBModelAdmin)
  390. admin.site.register(Publisher, PublisherAdmin)
  391. othersite = admin.Site('othersite')
  392. othersite.register(Publisher, MultiDBModelAdmin)
  393. This example sets up two admin sites. On the first site, the
  394. ``Author`` and ``Publisher`` objects are exposed; ``Publisher``
  395. objects have an tabular inline showing books published by that
  396. publisher. The second site exposes just publishers, without the
  397. inlines.