-
-
Save W1773ND/ebb43b6e134da0ac58f24a07e2cdbe4e 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment