將 pk 值設為 None 即可:
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
blog.pk = None
blog.save() # blog.pk == 2
如果涉及到繼承的話潮饱,必須將 pk 和 id 的值都設為 None:
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
django_blog.pk = None
django_blog.id = None
django_blog.save() # django_blog.pk == 4
需要注意的是:這種方法不會復制相關對象更啄。如果想復制相關對象(類似多對多)的話舒憾,需要像下面這樣镀钓。例如,Entry 與 Author 是多對多關系:
entry = Entry.objects.all()[0] # some previous entry
old_authors = entry.authors.all()
entry.pk = None
entry.save()
entry.authors.set(old_authors)
參考文檔:
https://docs.djangoproject.com/en/dev/topics/db/queries/#copying-model-instances