Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Created April 26, 2018 05:44
Show Gist options
  • Save hirokiky/ed1f662a136843905ae4e7462b3d1400 to your computer and use it in GitHub Desktop.
Save hirokiky/ed1f662a136843905ae4e7462b3d1400 to your computer and use it in GitHub Desktop.
Detecting changes of model field values.
""" Detect changes of Django Models.
"""
class ChangeDetector:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._dirty_fields = {f: False for f in self._get_field_names()}
self._inited = True
def __setattr__(self, name, value):
super().__setattr__(name, value)
if hasattr(self, '_inited'):
if name in self._get_field_names():
self._dirty_fields[name] = True
def _get_field_names(self):
return (f.name for f in self._meta.fields)
def is_dirty(self, fields=None):
fields = fields or self._get_field_names()
return any(self._dirty_fields[f] for f in fields)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment