Skip to content

Commit

Permalink
Add ignore_empty Parameter to has_changed Method
Browse files Browse the repository at this point in the history
  • Loading branch information
Mng-dev-ai committed May 26, 2024
1 parent 324ea2b commit 73d3395
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions model_utils/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,17 @@ def current(self, fields=None):

return {f: self.get_field_value(f) for f in fields}

def has_changed(self, field):
def has_changed(self, field, ignore_empty=True):
"""Returns ``True`` if field has changed from currently saved value"""
if field in self.fields:
# deferred fields haven't changed
if field in self.deferred_fields and field not in self.instance.__dict__:
return False
return self.previous(field) != self.get_field_value(field)
current_value = self.get_field_value(field)
previous_value = self.previous(field)
if ignore_empty and (previous_value is None and current_value == '' or previous_value == '' and current_value is None):
return False
return previous_value != current_value
else:
raise FieldError('field "%s" not tracked' % field)

Expand Down Expand Up @@ -353,12 +357,16 @@ def __get__(self, instance, owner):

class ModelInstanceTracker(FieldInstanceTracker):

def has_changed(self, field):
def has_changed(self, field, ignore_empty=True):
"""Returns ``True`` if field has changed from currently saved value"""
if not self.instance.pk:
return True
elif field in self.saved_data:
return self.previous(field) != self.get_field_value(field)
current_value = self.get_field_value(field)
previous_value = self.previous(field)
if ignore_empty and (previous_value is None and current_value == '' or previous_value == '' and current_value is None):
return False
return previous_value != current_value
else:
raise FieldError('field "%s" not tracked' % field)

Expand Down

0 comments on commit 73d3395

Please sign in to comment.