djangodjango-modelsdjango-reversion

How to restore files from secondary model when using Reversion app (DJANGO)


I have 2 models:

Model1(models.Model):

and 

Model2(models.Model):
fk = models.ForeignKey("Model1",  on_delete=models.CASCADE)
image  = models. ImageField(…..)

I use Reversion app to restore all deleted data and both models are registered in admin with Version admin. It works but when I restore any entry of model1 it would not restore actual files from Imagefield of the Model2. Thats reasonable because they are deleted by CASCADE. If I set on_delete = DO_NOTHING, it would rise integrity error as Postgree supports cross table integrity protection. Thats reasonable as well. If I use SET_NULL , then Reversion would not be able correctly restore images as it would loose foreignkey ID obviously. Question is how to restore associated images of the Model2 within data of the Model1 by Reversion or alternatively keep foreignkey ID of the Model2’s images intact if I use something outside CASCADE in order to not delete the images from the file system?

Thank you!


Solution

  • I have made an additional field that would store foreighkey id and on_delete i set to "set_null" And i have chancged delelete method in model, so that when reversion would try to restore model it would triger "save" method and fk id would be filled back from the memory field.

    
    
        def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
            if self.boat and not self.memory:
                self.memory = self.boat_id
            elif not self.boat and self.memory:
                self.boat_id = self.memory
            elif self.boat and self.memory and self.boat_id != self.memory:
                self.memory = self.boat_id
            models.Model.save(self, force_insert=False, force_update=False, using=None,
                              update_fields=None)