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

File 4027-copy-model-docs.diff, 1.6 KB (added by Tomek Paczkowski, 13 years ago)

(Git) diff with documentation update describing copying model instances

  • docs/topics/db/queries.txt

    diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt
    index 3457913..7c98509 100644
    a b complete query set::  
    810810
    811811    Entry.objects.all().delete()
    812812
     813.. _topics-db-queries-copy:
     814
     815Copying model instances
     816=======================
     817
     818Although there is no built-in method for copying models instances, it is
     819possible to easily create new instance with all fields' values copied. In the
     820simplest case, you can just set ``pk`` to ``None``. Using our blog example::
     821
     822    blog = Blog(name='My blog', tagline='Blogging is easy')
     823    blog.save() # post.pk == 1
     824
     825    blog.pk = None
     826    blog.save() # post.pk == 2
     827
     828Things get more complicated if you use inheritance. Consider subclass of
     829``Blog``::
     830
     831    class ThemeBlog(Blog):
     832        theme = models.CharField(max_length=200)
     833
     834    django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme = 'python')
     835    django_blog.save() # django_blog.pk == 3
     836
     837Due to how inheritance works, you have to set both ``pk`` and ``id`` to None::
     838
     839    django_blog.pk = None
     840    django_blog.id = None
     841    django_blog.save() # django_blog.pk == 4
     842
     843This process does not copy related objects. If you want to copy relations,
     844you have to write little more code. In our example ``Entry`` has many to many
     845field to ``Author``::
     846
     847    entry = Entry.objects.all()[0] # some previous entry
     848    old_authors = entry.authors.all()
     849    entry.pk = None
     850    entry.save()
     851    entry.authors = old_authors # saves new many2many relations
     852
    813853.. _topics-db-queries-update:
    814854
    815855Updating multiple objects at once
Back to Top