我正在恢复文档中指定的模型实例:
# In a DRF ViewSet, although I don't think that should matter...
instance = self.get_object()
# Find the historical record I want
desired_record = instance.history.first().prev_record
# Get the instance from it (I removed code handling the edge case of no prior history, for question clarity)
desired_instance = desired_record.instance
# EDIT, I have also tried
# desired_instance = instance.history.most_recent()
# which exhibits the same problem on save
# Include a changelog comment
desired_instance._change_reason = "Reverted to previous"
# Update the instance
desired_instance.save()
但是,这会产生错误:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "projects_configuration_pkey"
DETAIL: Key (id)=(9ffc4e31-e714-4258-95dd-a196a70bf301) already exists.
模型(在 app 中projects
)如下所示:
class Configuration(models.Model)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created = models.DateTimeField(editable=False, auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
name = models.CharField(blank=False, null=False, max_length=60)
当我使用该instance.history.as_of(<datetime>)
方法时,也会出现同样的问题。
DSH 似乎试图插入一条新记录,而不是将现有记录更新为以前的状态。这里发生了什么?