Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RodolfoSilva/e5c6737c87be9afa46f10b36414e1819 to your computer and use it in GitHub Desktop.
Save RodolfoSilva/e5c6737c87be9afa46f10b36414e1819 to your computer and use it in GitHub Desktop.
check if django model fields changed after save
def DjangoModel(models.Model):
@classmethod
def from_db(cls, db, field_names, values):
instance = super().from_db(db, field_names, values)
instance._state.adding = False
instance._state.db = db
instance._old_values = dict(zip(field_names, values))
return instance
def data_changed(self, fields):
"""
example:
if self.data_changed(['street', 'street_no', 'zip_code', 'city', 'country']):
print("one of the fields changed")
returns true if the model saved the first time and _old_values doesnt exist
:param fields:
:return:
"""
if hasattr(self, '_old_values'):
if not self.id or not self._old_values:
return True
for field in fields:
if getattr(self, field) != self._old_values[field]:
return True
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment