I am a big fan of django-simple-history, but I do not seem to be able to get "save_without_historical_record" to work properly when I use it inside the default save() method of a model.
I have a model such as this
class NzPlasmid (models.Model):
...
plasmid_map = models.FileField("Plasmid Map (max. 2 MB)", upload_to="temp/", blank=True)
history = HistoricalRecords()
...
It has a custom save() method, which renames plasmid_map with the id of the newly created object. In order to do that, I save the object the first time to get its id, then use that to rename plasmid_map. I do not want to save a historical record for the first save, but only for the second. My custom save() method looks like this
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)
which does not work, as I still get "duplicate" historical records everytime a plasmid is created.
Thanks a lot in advance.
I solved the issue by modifying the save_model
method in my admin.py
. When a new plasmid object that has a map is created, generating two historical records due to the renaming of plasmid_map
, I delete the first one, which contains the "wrong" plasmid_map name, and change the history_type of the second, from changed (~) to created (+):
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()