【问题标题】:django-simple-history, saving without historical record not workingdjango-simple-history,没有历史记录的保存不起作用
【发布时间】:2018-12-02 15:06:57
【问题描述】:

我是 django-simple-history 的忠实粉丝,但是当我在模型的默认 save() 方法中使用“save_without_historical_record”时,我似乎无法正常工作。

我有一个这样的模型

class NzPlasmid (models.Model):
    ...
    plasmid_map = models.FileField("Plasmid Map (max. 2 MB)", upload_to="temp/", blank=True)
    history = HistoricalRecords()
    ...

它有一个自定义的 save() 方法,它用新创建的对象的 id 重命名质粒映射。为了做到这一点,我第一次保存对象以获取它的 id,然后用它来重命名质粒_map。我不想为第一次保存保存历史记录,而只想为第二次保存。我的自定义 save() 方法如下所示

def save(self, force_insert=False, force_update=False):

    self.skip_history_when_saving = True
    super(NzPlasmid, self).save(force_insert, force_update)

    ... some rename magic here ...

    del self.skip_history_when_saving
    super(NzPlasmid, self).save(force_insert, force_update)

这不起作用,因为每次创建质粒时我仍然会得到“重复”的历史记录。

非常感谢。

【问题讨论】:

    标签: django-simple-history


    【解决方案1】:

    第一次保存时,您正在创建对象。但是,根据this line,如果对象正在更新而不是创建,则只能不保存历史记录。您可以尝试的一种解决方法是使用here 描述的pre_create_historical_record 信号。这有点 hacky,但您可以在下面的 apps.py 文件中包含信号处理代码:

    def update_plasmid_map_and_save_instance(sender, instance, history_instance):
        # instance should have id here
    
        ... some rename magic on your instance model...
    
        history_instance.plasmid_map = instance.plasmid_map
    
        instance.save_without_historical_record()
    
    
    # in apps.py
    class TestsConfig(AppConfig):
         def ready(self):
             from ..models import HistoricalNzPlasmid
    
             pre_create_historical_record.connect(
                 update_plasmid_map_and_save_instance,
                 sender=HistoricalNzPlasmid,
                 dispatch_uid='update_plasmid_map_on_history'
             )
    

    然后您就不必在NzPlasmid 上覆盖save。这有点 hacky,但它应该可以工作。

    【讨论】:

    • 我明白了!这解释了我观察到的许多行为。我会试试你的建议。非常感谢
    • @NicolaZilio 运气好吗?
    • 是的,但我最终实现了一个不同的解决方案,我希望,它比你建议的要少一点黑客。请参阅下面的帖子
    【解决方案2】:

    我通过修改admin.py 中的save_model 方法解决了这个问题。当创建一个具有映射的新质粒对象时,由于plasmid_map 的重命名而生成了两条历史记录,我删除了第一个,其中包含“错误”的质粒映射名称,并更改了第二个的历史记录类型,从更改(~) 到创建 (+):

    def save_model(self, request, obj, form, change):
    
        rename_and_preview = False
        new_obj = False
    
        if obj.pk == None:
            if obj.plasmid_map:
                rename_and_preview = True
                new_obj = True
            obj.save()
    
            ... some rename magic here ...
    
            if new_obj:
                obj.history.last().delete()
                history_obj = obj.history.first()
                history_obj.history_type = "+"
                history_obj.save()
    

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 2020-10-10
      • 2014-08-04
      • 1970-01-01
      • 2011-01-05
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多