Diff mixin to detect changes in Django models instances
Suppose you change your Django model instance, how do you know if the data actually changed? There are a few ways to achieve this, for example using django-simple-history which will add a database entry for every change to keep history.
However, you don't necessarily need to store this information in the database, as you can also copy the original data before changing the object. I've made a simple mixin that will copy the original from the database and stores it on the object itself:
class SomeModel(DiffMixin, models.Model):
some_attribute = models.IntegerField()
instance = SomeModel()
instance.some_attribute = 1
instance.some_attribute = 2
The mixin copies the original just before saving and deleting and keeps the latest around as long as the object lives as
You can expand on the mixin by for example providing more advanced comparison over all fields. When serializing the current and the original to a dictionary, dictdiffer.diff() could be a tool to establish a diff between the two.
Feel free to use and tweak my DiffMixin to your own needs: