From 73d3395817535065f2a132539bcf68f3799752c5 Mon Sep 17 00:00:00 2001 From: Mng <50384638+Mng-dev-ai@users.noreply.github.com> Date: Sun, 26 May 2024 16:21:35 +0300 Subject: [PATCH] Add ignore_empty Parameter to has_changed Method --- model_utils/tracker.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/model_utils/tracker.py b/model_utils/tracker.py index 5136990d..0339e4c8 100644 --- a/model_utils/tracker.py +++ b/model_utils/tracker.py @@ -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) @@ -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)