Automatically create new revisions of django model on save.

I have a use case I am investigating where saving an object should mark the original object as deleted, and save a new copy.

Using django, this is suprisingly easy to achieve.

Here is a simple model that does just that:

 1 from django.db import models
 2 class AutoSave(models.Model):
 3     name = models.CharField(max_length=64)
 4     active = models.BooleanField(default=True)
 5     previous = models.ForeignKey('AutoSave', null=True, blank=True,
 6         related_name='subsequent')
 8     def save(self, *args, **kwargs):
 9         if
10             self.previous_id =
11             AutoSave.objects.filter(
12    = None
13         super(AutoSave, self).save(*args, **kwargs)

The important bits are that there is a boolean field called active, which can be used to soft-delete, as well as to indicate that this is the most recent revision of an object. There is also a reference to the previous version.

When an object is saved, we look for an existing primary key. Django uses this to determine if we are doing an INSERT or UPDATE. We want to get a reference to the current revision, then update the database version of that revision to be inactive, and then ensure the current data will create a new database record.

This is obviously a bit of a simplification, but the only way I would change it might be to see if no fields have changed, in which case we don’t need to really save a new revision.