Skip to main content

Command Palette

Search for a command to run...

Diff mixin to detect changes in Django models instances

Updated
J

Made my first website in Microsoft Word at age 13, when I discovered the "save as html" button. Since then I've journeyed various computing languages, eventually settling for Python. I love diving into the core of my favorite framework - Django - discover and writing about new stuff.

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.save()

instance.some_attribute = 2
instance.is_changed('some_attribute')

The mixin copies the original just before saving and deleting and keeps the latest around as long as the object lives as _original .

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:

A

Very good piece of work