multi-db.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. ==================
  2. Multiple databases
  3. ==================
  4. .. versionadded:: 1.2
  5. This topic guide describes Django's support for interacting with
  6. multiple databases. Most of the rest of Django's documentation assumes
  7. you are interacting with a single database. If you want to interact
  8. with multiple databases, you'll need to take some additional steps.
  9. Defining your databases
  10. =======================
  11. The first step to using more than one database with Django is to tell
  12. Django about the database servers you'll be using. This is done using
  13. the :setting:`DATABASES` setting. This setting maps database aliases,
  14. which are a way to refer to a specific database throughout Django, to
  15. a dictionary of settings for that specific connection. The settings in
  16. the inner dictionaries are described fully in the :setting:`DATABASES`
  17. documentation.
  18. Databases can have any alias you choose. However, the alias
  19. ``default`` has special significance. Django uses the database with
  20. the alias of ``default`` when no other database has been selected. If
  21. you don't have a ``default`` database, you need to be careful to
  22. always specify the database that you want to use.
  23. The following is an example ``settings.py`` snippet defining two
  24. databases -- a default PostgreSQL database and a MySQL database called
  25. ``users``:
  26. .. code-block:: python
  27. DATABASES = {
  28. 'default': {
  29. 'NAME': 'app_data',
  30. 'ENGINE': 'django.db.backends.postgresql_psycopg2',
  31. 'USER': 'postgres_user',
  32. 'PASSWORD': 's3krit'
  33. },
  34. 'users': {
  35. 'NAME': 'user_data',
  36. 'ENGINE': 'django.db.backends.mysql',
  37. 'USER': 'mysql_user',
  38. 'PASSWORD': 'priv4te'
  39. }
  40. }
  41. If you attempt to access a database that you haven't defined in your
  42. :setting:`DATABASES` setting, Django will raise a
  43. ``django.db.utils.ConnectionDoesNotExist`` exception.
  44. Synchronizing your databases
  45. ============================
  46. The :djadmin:`syncdb` management command operates on one database at a
  47. time. By default, it operates on the ``default`` database, but by
  48. providing a :djadminopt:`--database` argument, you can tell syncdb to
  49. synchronize a different database. So, to synchronize all models onto
  50. all databases in our example, you would need to call::
  51. $ ./manage.py syncdb
  52. $ ./manage.py syncdb --database=users
  53. If you don't want every application to be synchronized onto a
  54. particular database, you can define a :ref:`database
  55. router<topics-db-multi-db-routing>` that implements a policy
  56. constraining the availability of particular models.
  57. Alternatively, if you want fine-grained control of synchronization,
  58. you can pipe all or part of the output of :djadmin:`sqlall` for a
  59. particular application directly into your database prompt, like this::
  60. $ ./manage.py sqlall sales | ./manage.py dbshell
  61. Using other management commands
  62. -------------------------------
  63. The other ``django-admin.py`` commands that interact with the database
  64. operate in the same way as :djadmin:`syncdb` -- they only ever operate
  65. on one database at a time, using :djadminopt:`--database` to control
  66. the database used.
  67. .. _topics-db-multi-db-routing:
  68. Automatic database routing
  69. ==========================
  70. The easiest way to use multiple databases is to set up a database
  71. routing scheme. The default routing scheme ensures that objects remain
  72. 'sticky' to their original database (i.e., an object retrieved from
  73. the ``foo`` database will be saved on the same database). The default
  74. routing scheme ensures that if a database isn't specified, all queries
  75. fall back to the ``default`` database.
  76. You don't have to do anything to activate the default routing scheme
  77. -- it is provided 'out of the box' on every Django project. However,
  78. if you want to implement more interesting database allocation
  79. behaviors, you can define and install your own database routers.
  80. Database routers
  81. ----------------
  82. A database Router is a class that provides up to four methods:
  83. .. method:: db_for_read(model, **hints)
  84. Suggest the database that should be used for read operations for
  85. objects of type ``model``.
  86. If a database operation is able to provide any additional
  87. information that might assist in selecting a database, it will be
  88. provided in the ``hints`` dictionary. Details on valid hints are
  89. provided :ref:`below <topics-db-multi-db-hints>`.
  90. Returns None if there is no suggestion.
  91. .. method:: db_for_write(model, **hints)
  92. Suggest the database that should be used for writes of objects of
  93. type Model.
  94. If a database operation is able to provide any additional
  95. information that might assist in selecting a database, it will be
  96. provided in the ``hints`` dictionary. Details on valid hints are
  97. provided :ref:`below <topics-db-multi-db-hints>`.
  98. Returns None if there is no suggestion.
  99. .. method:: allow_relation(obj1, obj2, **hints)
  100. Return True if a relation between obj1 and obj2 should be
  101. allowed, False if the relation should be prevented, or None if
  102. the router has no opinion. This is purely a validation operation,
  103. used by foreign key and many to many operations to determine if a
  104. relation should be allowed between two objects.
  105. .. method:: allow_syncdb(db, model)
  106. Determine if the ``model`` should be synchronized onto the
  107. database with alias ``db``. Return True if the model should be
  108. synchronized, False if it should not be synchronized, or None if
  109. the router has no opinion. This method can be used to determine
  110. the availability of a model on a given database.
  111. A router doesn't have to provide *all* these methods -- it may omit one
  112. or more of them. If one of the methods is omitted, Django will skip
  113. that router when performing the relevant check.
  114. .. _topics-db-multi-db-hints:
  115. Hints
  116. ~~~~~
  117. The hints received by the database router can be used to decide which
  118. database should receive a given request.
  119. At present, the only hint that will be provided is ``instance``, an
  120. object instance that is related to the read or write operation that is
  121. underway. This might be the instance that is being saved, or it might
  122. be an instance that is being added in a many-to-many relation. In some
  123. cases, no instance hint will be provided at all. The router checks for
  124. the existence of an instance hint, and determine if that hint should be
  125. used to alter routing behavior.
  126. Using routers
  127. -------------
  128. Database routers are installed using the :setting:`DATABASE_ROUTERS`
  129. setting. This setting defines a list of class names, each specifying a
  130. router that should be used by the master router
  131. (``django.db.router``).
  132. The master router is used by Django's database operations to allocate
  133. database usage. Whenever a query needs to know which database to use,
  134. it calls the master router, providing a model and a hint (if
  135. available). Django then tries each router in turn until a database
  136. suggestion can be found. If no suggestion can be found, it tries the
  137. current ``_state.db`` of the hint instance. If a hint instance wasn't
  138. provided, or the instance doesn't currently have database state, the
  139. master router will allocate the ``default`` database.
  140. An example
  141. ----------
  142. .. admonition:: Example purposes only!
  143. This example is intended as a demonstration of how the router
  144. infrastructure can be used to alter database usage. It
  145. intentionally ignores some complex issues in order to
  146. demonstrate how routers are used.
  147. This example won't work if any of the models in ``myapp`` contain
  148. relationships to models outside of the ``other`` database.
  149. :ref:`Cross-database relationships <no_cross_database_relations>`
  150. introduce referential integrity problems that Django can't
  151. currently handle.
  152. The master/slave configuration described is also flawed -- it
  153. doesn't provide any solution for handling replication lag (i.e.,
  154. query inconsistencies introduced because of the time taken for a
  155. write to propagate to the slaves). It also doesn't consider the
  156. interaction of transactions with the database utilization strategy.
  157. So - what does this mean in practice? Say you want ``myapp`` to
  158. exist on the ``other`` database, and you want all other models in a
  159. master/slave relationship between the databases ``master``, ``slave1`` and
  160. ``slave2``. To implement this, you would need 2 routers::
  161. class MyAppRouter(object):
  162. """A router to control all database operations on models in
  163. the myapp application"""
  164. def db_for_read(self, model, **hints):
  165. "Point all operations on myapp models to 'other'"
  166. if model._meta.app_label == 'myapp':
  167. return 'other'
  168. return None
  169. def db_for_write(self, model, **hints):
  170. "Point all operations on myapp models to 'other'"
  171. if model._meta.app_label == 'myapp':
  172. return 'other'
  173. return None
  174. def allow_relation(self, obj1, obj2, **hints):
  175. "Allow any relation if a model in myapp is involved"
  176. if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
  177. return True
  178. return None
  179. def allow_syncdb(self, db, model):
  180. "Make sure the myapp app only appears on the 'other' db"
  181. if db == 'other':
  182. return model._meta.app_label == 'myapp'
  183. elif model._meta.app_label == 'myapp':
  184. return False
  185. return None
  186. class MasterSlaveRouter(object):
  187. """A router that sets up a simple master/slave configuration"""
  188. def db_for_read(self, model, **hints):
  189. "Point all read operations to a random slave"
  190. return random.choice(['slave1','slave2'])
  191. def db_for_write(self, model, **hints):
  192. "Point all write operations to the master"
  193. return 'master'
  194. def allow_relation(self, obj1, obj2, **hints):
  195. "Allow any relation between two objects in the db pool"
  196. db_list = ('master','slave1','slave2')
  197. if obj1._state.db in db_list and obj2._state.db in db_list:
  198. return True
  199. return None
  200. def allow_syncdb(self, db, model):
  201. "Explicitly put all models on all databases."
  202. return True
  203. Then, in your settings file, add the following (substituting ``path.to.`` with
  204. the actual python path to the module where you define the routers)::
  205. DATABASE_ROUTERS = ['path.to.MyAppRouter', 'path.to.MasterSlaveRouter']
  206. The order in which routers are processed is significant. Routers will
  207. be queried in the order the are listed in the
  208. :setting:`DATABASE_ROUTERS` setting . In this example, the
  209. ``MyAppRouter`` is processed before the ``MasterSlaveRouter``, and as a
  210. result, decisions concerning the models in ``myapp`` are processed
  211. before any other decision is made. If the :setting:`DATABASE_ROUTERS`
  212. setting listed the two routers in the other order,
  213. ``MasterSlaveRouter.allow_syncdb()`` would be processed first. The
  214. catch-all nature of the MasterSlaveRouter implementation would mean
  215. that all models would be available on all databases.
  216. With this setup installed, lets run some Django code::
  217. >>> # This retrieval will be performed on the 'credentials' database
  218. >>> fred = User.objects.get(username='fred')
  219. >>> fred.first_name = 'Frederick'
  220. >>> # This save will also be directed to 'credentials'
  221. >>> fred.save()
  222. >>> # These retrieval will be randomly allocated to a slave database
  223. >>> dna = Person.objects.get(name='Douglas Adams')
  224. >>> # A new object has no database allocation when created
  225. >>> mh = Book(title='Mostly Harmless')
  226. >>> # This assignment will consult the router, and set mh onto
  227. >>> # the same database as the author object
  228. >>> mh.author = dna
  229. >>> # This save will force the 'mh' instance onto the master database...
  230. >>> mh.save()
  231. >>> # ... but if we re-retrieve the object, it will come back on a slave
  232. >>> mh = Book.objects.get(title='Mostly Harmless')
  233. Manually selecting a database
  234. =============================
  235. Django also provides an API that allows you to maintain complete control
  236. over database usage in your code. A manually specified database allocation
  237. will take priority over a database allocated by a router.
  238. Manually selecting a database for a ``QuerySet``
  239. ------------------------------------------------
  240. You can select the database for a ``QuerySet`` at any point in the
  241. ``QuerySet`` "chain." Just call ``using()`` on the ``QuerySet`` to get
  242. another ``QuerySet`` that uses the specified database.
  243. ``using()`` takes a single argument: the alias of the database on
  244. which you want to run the query. For example::
  245. >>> # This will run on the 'default' database.
  246. >>> Author.objects.all()
  247. >>> # So will this.
  248. >>> Author.objects.using('default').all()
  249. >>> # This will run on the 'other' database.
  250. >>> Author.objects.using('other').all()
  251. Selecting a database for ``save()``
  252. -----------------------------------
  253. Use the ``using`` keyword to ``Model.save()`` to specify to which
  254. database the data should be saved.
  255. For example, to save an object to the ``legacy_users`` database, you'd
  256. use this::
  257. >>> my_object.save(using='legacy_users')
  258. If you don't specify ``using``, the ``save()`` method will save into
  259. the default database allocated by the routers.
  260. Moving an object from one database to another
  261. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  262. If you've saved an instance to one database, it might be tempting to
  263. use ``save(using=...)`` as a way to migrate the instance to a new
  264. database. However, if you don't take appropriate steps, this could
  265. have some unexpected consequences.
  266. Consider the following example::
  267. >>> p = Person(name='Fred')
  268. >>> p.save(using='first') # (statement 1)
  269. >>> p.save(using='second') # (statement 2)
  270. In statement 1, a new ``Person`` object is saved to the ``first``
  271. database. At this time, ``p`` doesn't have a primary key, so Django
  272. issues a SQL ``INSERT`` statement. This creates a primary key, and
  273. Django assigns that primary key to ``p``.
  274. When the save occurs in statement 2, ``p`` already has a primary key
  275. value, and Django will attempt to use that primary key on the new
  276. database. If the primary key value isn't in use in the ``second``
  277. database, then you won't have any problems -- the object will be
  278. copied to the new database.
  279. However, if the primary key of ``p`` is already in use on the
  280. ``second`` database, the existing object in the ``second`` database
  281. will be overridden when ``p`` is saved.
  282. You can avoid this in two ways. First, you can clear the primary key
  283. of the instance. If an object has no primary key, Django will treat it
  284. as a new object, avoiding any loss of data on the ``second``
  285. database::
  286. >>> p = Person(name='Fred')
  287. >>> p.save(using='first')
  288. >>> p.pk = None # Clear the primary key.
  289. >>> p.save(using='second') # Write a completely new object.
  290. The second option is to use the ``force_insert`` option to ``save()``
  291. to ensure that Django does a SQL ``INSERT``::
  292. >>> p = Person(name='Fred')
  293. >>> p.save(using='first')
  294. >>> p.save(using='second', force_insert=True)
  295. This will ensure that the person named ``Fred`` will have the same
  296. primary key on both databases. If that primary key is already in use
  297. when you try to save onto the ``second`` database, an error will be
  298. raised.
  299. Selecting a database to delete from
  300. -----------------------------------
  301. By default, a call to delete an existing object will be executed on
  302. the same database that was used to retrieve the object in the first
  303. place::
  304. >>> u = User.objects.using('legacy_users').get(username='fred')
  305. >>> u.delete() # will delete from the `legacy_users` database
  306. To specify the database from which a model will be deleted, pass a
  307. ``using`` keyword argument to the ``Model.delete()`` method. This
  308. argument works just like the ``using`` keyword argument to ``save()``.
  309. For example, if you're migrating a user from the ``legacy_users``
  310. database to the ``new_users`` database, you might use these commands::
  311. >>> user_obj.save(using='new_users')
  312. >>> user_obj.delete(using='legacy_users')
  313. Using managers with multiple databases
  314. --------------------------------------
  315. Use the ``db_manager()`` method on managers to give managers access to
  316. a non-default database.
  317. For example, say you have a custom manager method that touches the
  318. database -- ``User.objects.create_user()``. Because ``create_user()``
  319. is a manager method, not a ``QuerySet`` method, you can't do
  320. ``User.objects.using('new_users').create_user()``. (The
  321. ``create_user()`` method is only available on ``User.objects``, the
  322. manager, not on ``QuerySet`` objects derived from the manager.) The
  323. solution is to use ``db_manager()``, like this::
  324. User.objects.db_manager('new_users').create_user(...)
  325. ``db_manager()`` returns a copy of the manager bound to the database you specify.
  326. Using ``get_query_set()`` with multiple databases
  327. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  328. If you're overriding ``get_query_set()`` on your manager, be sure to
  329. either call the method on the parent (using ``super()``) or do the
  330. appropriate handling of the ``_db`` attribute on the manager (a string
  331. containing the name of the database to use).
  332. For example, if you want to return a custom ``QuerySet`` class from
  333. the ``get_query_set`` method, you could do this::
  334. class MyManager(models.Manager):
  335. def get_query_set(self):
  336. qs = CustomQuerySet(self.model)
  337. if self._db is not None:
  338. qs = qs.using(self._db)
  339. return qs
  340. Exposing multiple databases in Django's admin interface
  341. =======================================================
  342. Django's admin doesn't have any explicit support for multiple
  343. databases. If you want to provide an admin interface for a model on a
  344. database other than that that specified by your router chain, you'll
  345. need to write custom :class:`~django.contrib.admin.ModelAdmin` classes
  346. that will direct the admin to use a specific database for content.
  347. ``ModelAdmin`` objects have five methods that require customization for
  348. multiple-database support::
  349. class MultiDBModelAdmin(admin.ModelAdmin):
  350. # A handy constant for the name of the alternate database.
  351. using = 'other'
  352. def save_model(self, request, obj, form, change):
  353. # Tell Django to save objects to the 'other' database.
  354. obj.save(using=self.using)
  355. def delete_model(self, request, obj):
  356. # Tell Django to delete objects from the 'other' database
  357. obj.delete(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.
  405. Using raw cursors with multiple databases
  406. =========================================
  407. If you are using more than one database you can use
  408. ``django.db.connections`` to obtain the connection (and cursor) for a
  409. specific database. ``django.db.connections`` is a dictionary-like
  410. object that allows you to retrieve a specific connection using its
  411. alias::
  412. from django.db import connections
  413. cursor = connections['my_db_alias'].cursor()
  414. Limitations of multiple databases
  415. =================================
  416. .. _no_cross_database_relations:
  417. Cross-database relations
  418. ------------------------
  419. Django doesn't currently provide any support for foreign key or
  420. many-to-many relationships spanning multiple databases. If you
  421. have used a router to partition models to different databases,
  422. any foreign key and many-to-many relationships defined by those
  423. models must be internal to a single database.
  424. This is because of referential integrity. In order to maintain a
  425. relationship between two objects, Django needs to know that the
  426. primary key of the related object is valid. If the primary key is
  427. stored on a separate database, it's not possible to easily evaluate
  428. the validity of a primary key.
  429. If you're using Postgres, Oracle, or MySQL with InnoDB, this is
  430. enforced at the database integrity level -- database level key
  431. constraints prevent the creation of relations that can't be validated.
  432. However, if you're using SQLite or MySQL with MyISAM tables, there is
  433. no enforced referential integrity; as a result, you may be able to
  434. 'fake' cross database foreign keys. However, this configuration is not
  435. officially supported by Django.