0

我是 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)

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

提前非常感谢。

4

2 回答 2

0

第一次保存时,您正在创建对象。但是,根据这一行,如果对象正在更新而不是创建,则只能保存而不保存历史记录。您可以尝试的一种解决方法是使用此处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'
         )

然后你就不必覆盖saveon NzPlasmid。这有点hacky,但它应该可以工作。

于 2018-12-13T15:58:58.050 回答
0

我通过修改save_model我的admin.py. 当创建一个具有映射的新质粒对象时,由于重命名生成了两条历史记录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()
于 2019-01-26T21:18:57.610 回答