Skip to content

Instantly share code, notes, and snippets.

@alican
Last active September 17, 2023 08:46
Show Gist options
  • Save alican/cb9e81699e4ad1af81ca897ae500393b to your computer and use it in GitHub Desktop.
Save alican/cb9e81699e4ad1af81ca897ae500393b to your computer and use it in GitHub Desktop.
check if django model fields changed after save
class 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.pk 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
@hodossy
Copy link

hodossy commented Feb 12, 2020

Hi! Nice gist, thanks for creating it! I just noticed that the return False statement on line 31 is wrongly indented. It returns right after the first field is checked. I would also use self.pk instead of self.id since that is more general.

@ewoudenberg
Copy link

Yes, very nice, thanks. I also noticed the class def is wrong:

def DjangoModel(models.Model):

should be

class DjangoModel(models.Model):

@alican
Copy link
Author

alican commented Sep 22, 2020

Thank you. I updated the code.

@GeVhoo
Copy link

GeVhoo commented Jun 30, 2021

Thank you! It was a salvation for me.

@PUYUP
Copy link

PUYUP commented Jul 25, 2021

Very helpful, thank you!

@aphisit-kha
Copy link

Thank you!

@Hilmi34
Copy link

Hilmi34 commented Aug 22, 2022

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment