0

我正在恢复文档中指定的模型实例:

# 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 似乎试图插入一条新记录,而不是将现有记录更新为以前的状态。这里发生了什么?

4

1 回答 1

1

事实证明,这是一个与 UUIDField(django 3.0向后不兼容)相关的已知问题,有一个解决方法:

# Find the historical record you want (use `most_recent`, `as_of`, or whatever method)
desired_record = instance.history.first().prev_record 
desired_instance = desired_record.instance

# Include a changelog comment
desired_instance._change_reason = "Reverted to previous"

# Tell django >3.0 that it's being updated, not added
desired_instance._state.adding = False

# And force save it
desired_instance.save(force_update=True)
于 2020-12-11T16:13:02.273 回答