summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorJohannes Wilm <johanneswilm@gmail.com>2021-02-19 19:53:43 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2021-02-22 11:52:52 +0100
commitcf05f9f205e2dcbcaad10b24be94ad66c0523514 (patch)
tree4eb075cae2de2b46672d4c4fd61c2bdb4726804f /docs
parenteccf40a3038bb38c4fd0e7c3ada03e7a9a02c091 (diff)
[3.2.x] Refs #4027 -- Added Model._state.adding to docs about copying model instances.
Backport of 0fd05df7b5690fb1b675e1b4d9c92bb22ff74360 from master
Diffstat (limited to 'docs')
-rw-r--r--docs/topics/db/queries.txt10
1 files changed, 8 insertions, 2 deletions
diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt
index cc77a495a0..03d18214e5 100644
--- a/docs/topics/db/queries.txt
+++ b/docs/topics/db/queries.txt
@@ -1237,12 +1237,15 @@ 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 set ``pk`` to ``None``. Using our blog example::
+simplest case, you can set ``pk`` to ``None`` and
+:attr:`_state.adding <django.db.models.Model._state>` to ``True``. Using our
+blog example::
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
blog.pk = None
+ blog._state.adding = True
blog.save() # blog.pk == 2
Things get more complicated if you use inheritance. Consider a subclass of
@@ -1255,10 +1258,11 @@ Things get more complicated if you use inheritance. Consider a subclass of
django_blog.save() # django_blog.pk == 3
Due to how inheritance works, you have to set both ``pk`` and ``id`` to
-``None``::
+``None``, and ``_state.adding`` to ``True``::
django_blog.pk = None
django_blog.id = None
+ django_blog._state.adding = True
django_blog.save() # django_blog.pk == 4
This process doesn't copy relations that aren't part of the model's database
@@ -1269,6 +1273,7 @@ entry::
entry = Entry.objects.all()[0] # some previous entry
old_authors = entry.authors.all()
entry.pk = None
+ entry._state.adding = True
entry.save()
entry.authors.set(old_authors)
@@ -1278,6 +1283,7 @@ For example, assuming ``entry`` is already duplicated as above::
detail = EntryDetail.objects.all()[0]
detail.pk = None
+ detail._state.adding = True
detail.entry = entry
detail.save()