如何复制django模型实例,保留对原始实例的引用?

时间:2015-10-19 06:36:16

标签: django django-orm

The docs举一个复制模型实例的例子:

blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1

blog.pk = None
blog.save() # blog.pk == 2

在一个稍微复杂的场景中,我有一个Article可以指向Revision,它保留对其父级的引用(保留编辑的历史记录)。 我想复制现有的Revision,将副本parent设置为原始文件。

class Article:
    revision = models.OneToOneField('Revision')

class Revision:
    article = models.ForeignKey('Article')
    parent = models.ForeignKey('Revision', related_name='children')
    content = models.TextField()

article = get_some_article()
revision = article.revision # ideally I want this to dupe the python object
revision.pk = None # but this create a copy instead
revision.content += " edited"
revision.parent = article.revision # this is the apparent problem
revision.save()

我认为revision.parent = article.revision存在两个问题。一,它是一个自我参考,两个,它还没有被保存,所以不能被引用。

我可能会做这样的事情,除非实例被缓存(?):

parent = Revision.objects.get(pk=article.revision.pk) #get a duplicate
...
revision.parent = parent

但这很糟糕,因为它只涉及复制对象的整个额外查询。我该怎么做?

1 个答案:

答案 0 :(得分:0)

article = get_some_article()
revision = article.revision
revision.parent = revision # Set the parent to itself
revision.content += " edited"
revision.pk = None
revision.save()  # New revision with parent set to original
# Assuming you are keeping the latest revision reference in article you need to update that also.
article.revision = revision
article.save()