将 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
网友评论