.. _topics-db-multi-db:

==================
Multiple Databases
==================

.. versionadded:: TODO

This topic guide describes Django's support for interacting with multiple
databases.  Most of the rest of Django's documentation assumes you are
interacting with a single database.  While none of this documentation is
incorrect, to fully interact with multiple databases additional steps must be
taken.

Defining Your Databases
=======================

The first step to using more than one database with Django is to tell Django
about the database servers you'll be using.  This is done using the
:settings:`DATABASES` setting.  This setting maps database aliases, which are
a way to refer to a specific database throughout Django, to a dictionary of
settings for that specific connection.  The settings in the inner dictionaries
are described fully in the :settings:`DATABASES` documentation.  The important
thing to note is that your primary database should have the alias
``'default'``, and any additional databases you have can have whatever alias
you choose.

Selecting a Database for a ``Model``
====================================

In addition to the global default database for all models, it is possible to
select a default database on a per-model level.  This is done using the
``using`` option in a model's inner ``Meta`` class.  When provided this
database becomes the default database for all lookups, saves, and deletes for
this model.  It can be overiden on a per-query basis as described below.

Selecting a Database for a ``QuerySet``
=======================================

It is possible to select the database for a ``QuerySet`` at any point during
it's construction.  To choose the database that a query will be preformed
against simply call the ``using()`` method on the ``QuerySet`` with the sole
argument being the database alias.

Select a Database to Save a Model To
====================================

To choose what database to save a model to, provide a ``using`` keyword
argument to ``Model.save()``.  For example if you had a user model that you
wanted to save to the ``'legacy_users'`` database you would do::

    >>> user_obj.save(using='legacy_users')

To save the user.

Select a Database to Delete a Model From
=======================================

To select which database to delete a model from you also use a ``using``
keyword argument to the ``Model.delete()`` method, analogous to the ``using``
keyword argument to ``save()``.  For example if you were migrating a user from
the ``'legacy_users'`` database to the ``'new_users'`` database you might do::

    >>> user_obj.save(using='new_users')
    >>> usre_obj.delete(using='legacy_users')
