Skip to content

Instantly share code, notes, and snippets.

@Thyrst
Created May 1, 2020 12:17
Show Gist options
  • Save Thyrst/03d8889b97da6cb7e4a371a697b174b8 to your computer and use it in GitHub Desktop.
Save Thyrst/03d8889b97da6cb7e4a371a697b174b8 to your computer and use it in GitHub Desktop.
Mixin for watching field changes on Django models
class DiffMixin:
"""
Mixin for watching field changes
Loads default/original attributes defined in the `watched_fields` list into the `originals` dict.
Then we can check if a field has changed with the `has_field_changed` method.
We can also get the original value of a field directly from the `originals` dict.
Attributes:
watched_fields (list): Class attribute with fields watched for changes.
originals (dict): Instance attribute with original values of the fields.
"""
watched_fields = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.originals = {}
self.load_originals()
def load_originals(self):
for field in self.watched_fields:
self.originals[field] = getattr(self, field)
def has_field_changed(self, field):
return self.originals[field] != getattr(self, field)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
self.load_originals()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment