Created
May 1, 2020 12:17
-
-
Save Thyrst/03d8889b97da6cb7e4a371a697b174b8 to your computer and use it in GitHub Desktop.
Mixin for watching field changes on Django models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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