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() # blog.pk == 1 
 
blog.pk = None 
blog.save() # blog.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() ...

Get Mastering Django: Core now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.