【问题标题】:Django Simple History INSERTS rather than UPDATES when reverting a model恢复模型时,Django 简单历史记录插入而不是更新
【发布时间】:2020-12-11 14:53:18
【问题描述】:

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

# 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.

模型(在应用程序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 似乎试图插入一条新记录,而不是将现有记录更新为以前的状态。这是怎么回事?

【问题讨论】:

    标签: python django django-simple-history


    【解决方案1】:

    原来这是一个与 UUIDField 相关的 known issue(一个 django 3.0 backward incompatibility),有一个解决方法:

    # 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)
    

    【讨论】:

    • 嗯,是的。现在我记得当我在更新日志中看到它时,我不喜欢那个改变。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    相关资源
    最近更新 更多