Forked from alican/django_field_update_checker.txt
Created
November 20, 2019 00:28
-
-
Save RodolfoSilva/e5c6737c87be9afa46f10b36414e1819 to your computer and use it in GitHub Desktop.
check if django model fields changed after save
This file contains hidden or 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
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