1
0
mirror of https://github.com/django/django.git synced 2025-07-04 17:59:13 +00:00

[soc2009/multidb] Added documentation about the potential complications trying to migrate an object between databases. Patch from Russell Keith-Magee.

git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/multidb@11811 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Alex Gaynor 2009-12-12 02:09:11 +00:00
parent bee835fa44
commit 353e079792

View File

@ -46,6 +46,59 @@ wanted to save to the ``'legacy_users'`` database you would do::
To save the user.
Moving an object from one database to another
---------------------------------------------
If you have saved an instance to one database, it might be tempting to use
``save(using=...)`` as a way to migrate the instance to a new database. However,
if you don't take appropriate steps, this could have some unexpected consequences.
Consider the following example::
>>> p = Person(name='Fred')
>>> p.save(using='first') # (1)
# some other processing ...
>>> p.save(using='second') # (2)
In statement 1, a new Person object is saved to the ``first``
database. At this time, ``p`` doesn't have a primary key, so Django
issues a SQL ``INSERT`` statement. This creates a primary key, and
Django assigns that primary key to ``p``.
When the save occurs in statement 2, ``p`` already has a primary key
value, and Django will attempt to use that primary key on the new
database. If the primary key value isn't in use in the ``second``
database, then you won't have any problems -- the object will be
copied to the new databse.
However, if the primary key of ``p`` is already in use on the
``second`` database, the existing object on the ``second`` database
will be lost when ``p`` is saved.
There are two ways to avoid this outcome. Firstly, you can clear the
primary key of the instance. If an object has no primary key, Django
will treat it as a new object, avoiding any loss of data on the
``second`` database::
>>> p = Person(name='Fred')
>>> p.save(using='first')
# some other processing ...
>>> p.pk = None # Clear the PK
>>> p.save(using='second') # Write a completely new object
Secondly, you can use the ``force_insert`` option to ``save()`` to ensure that
Django does a SQL ``INSERT``::
>>> p = Person(name='Fred')
>>> p.save(using='first')
# some other processing ...
>>> p.save(using='second', force_insert=True)
This will ensure that the person named ``Fred`` will have the same
primary key on both databases. If that primary key is already in use
when you try to save onto the ``second`` database, an error will be
raised.
Select a Database to Delete a Model From
========================================