Code

Ticket #4027: 4027-copy-model-docs-text.diff

File 4027-copy-model-docs-text.diff, 1.6 KB (added by erikr, 3 years ago)

Same as last patch, tiny language corrections added.

Line 
1diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt
2index 3457913..7c98509 100644
3--- a/docs/topics/db/queries.txt
4+++ b/docs/topics/db/queries.txt
5@@ -810,6 +810,46 @@ complete query set::
6 
7     Entry.objects.all().delete()
8 
9+.. _topics-db-queries-copy:
10+
11+Copying model instances
12+=======================
13+
14+Although there is no built-in method for copying model instances, it is
15+possible to easily create new instance with all fields' values copied. In the
16+simplest case, you can just set ``pk`` to ``None``. Using our blog example::
17+
18+    blog = Blog(name='My blog', tagline='Blogging is easy')
19+    blog.save() # post.pk == 1
20+
21+    blog.pk = None
22+    blog.save() # post.pk == 2
23+
24+Things get more complicated if you use inheritance. Consider a subclass of
25+``Blog``::
26+
27+    class ThemeBlog(Blog):
28+        theme = models.CharField(max_length=200)
29+
30+    django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme = 'python')
31+    django_blog.save() # django_blog.pk == 3
32+
33+Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::
34+
35+    django_blog.pk = None
36+    django_blog.id = None
37+    django_blog.save() # django_blog.pk == 4
38+
39+This process does not copy related objects. If you want to copy relations,
40+you have to write a little bit more code. In our example, ``Entry`` has a many to many
41+field to ``Author``::
42+
43+    entry = Entry.objects.all()[0] # some previous entry
44+    old_authors = entry.authors.all()
45+    entry.pk = None
46+    entry.save()
47+    entry.authors = old_authors # saves new many2many relations
48+
49 .. _topics-db-queries-update:
50 
51 Updating multiple objects at once