Last active
September 17, 2023 08:46
-
-
Save alican/cb9e81699e4ad1af81ca897ae500393b to your computer and use it in GitHub Desktop.
check if django model fields changed after save
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 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 |
Thank you. I updated the code.
Thank you! It was a salvation for me.
Very helpful, thank you!
Thank you!
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, very nice, thanks. I also noticed the class def is wrong:
should be