| 813 | .. _topics-db-queries-copy: |
| 814 | |
| 815 | Copying model instances |
| 816 | ======================= |
| 817 | |
| 818 | Although there is no built-in method for copying models instances, it is |
| 819 | possible to easily create new instance with all fields' values copied. In the |
| 820 | simplest 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 | |
| 828 | Things 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 | |
| 837 | Due 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 | |
| 843 | This process does not copy related objects. If you want to copy relations, |
| 844 | you have to write little more code. In our example ``Entry`` has many to many |
| 845 | field 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 | |