美文网首页
复制/克隆一条查询结果,插入到数据库中

复制/克隆一条查询结果,插入到数据库中

作者: 与蟒唯舞 | 来源:发表于2019-08-21 14:12 被阅读0次

    将 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

    https://stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database

    相关文章

      网友评论

          本文标题:复制/克隆一条查询结果,插入到数据库中

          本文链接:https://www.haomeiwen.com/subject/swbbsctx.html