Skip to content

Commit

Permalink
Fixed #4027 - Document how to make copies of model instances
Browse files Browse the repository at this point in the history
Thanks to Marek Kubica for the report and initial patch, and to oinopion and
erikr for work on the patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17064 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
spookylukey committed Nov 1, 2011
1 parent 3b7a4c6 commit a97ecfd
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions docs/topics/db/queries.txt
Expand Up @@ -828,6 +828,46 @@ complete query set::


Entry.objects.all().delete() Entry.objects.all().delete()


.. _topics-db-queries-copy:

Copying model instances
=======================

Although there is no built-in method for copying model instances, it is
possible to easily create new instance with all fields' values copied. In the
simplest case, you can just set ``pk`` to ``None``. Using our blog example::

blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # post.pk == 1

blog.pk = None
blog.save() # post.pk == 2

Things get more complicated if you use inheritance. Consider a subclass of
``Blog``::

class ThemeBlog(Blog):
theme = models.CharField(max_length=200)

django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme = 'python')
django_blog.save() # django_blog.pk == 3

Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::

django_blog.pk = None
django_blog.id = None
django_blog.save() # django_blog.pk == 4

This process does not copy related objects. If you want to copy relations,
you have to write a little bit more code. In our example, ``Entry`` has a many to many
field to ``Author``::

entry = Entry.objects.all()[0] # some previous entry
old_authors = entry.authors.all()
entry.pk = None
entry.save()
entry.authors = old_authors # saves new many2many relations

.. _topics-db-queries-update: .. _topics-db-queries-update:


Updating multiple objects at once Updating multiple objects at once
Expand Down

2 comments on commit a97ecfd

@johanneswilm
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @spookylukey I realize this is an older commit, but shouldn't this also include setting entry._state.adding = True? This has become an issue for us in django-treebeard/django-treebeard#210

@spookylukey
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@johanneswilm it's entirely possible you are right - it would be best to open a ticket on https://code.djangoproject.com/

Please sign in to comment.