Skip to content
This repository has been archived by the owner on May 29, 2024. It is now read-only.

Commit

Permalink
SDE-5196 Save queries when checking m2m fields
Browse files Browse the repository at this point in the history
Add flag to for simple m2m tracking, saving us DB queries
  • Loading branch information
harry-kim authored and Harry Kim committed Mar 19, 2018
1 parent 42c8a6e commit d4047f2
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/dirtyfields/dirtyfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ class DirtyFieldsMixin(object):
# https://github.com/romgar/django-dirtyfields/issues/73
ENABLE_M2M_CHECK = False

# Flag to track M2M changes as a simple boolean; less accurate than
# ENABLE_M2M_CHECK as we're only tracking if m2m relations were updated,
# not whether they are dirty
ENABLE_BASIC_M2M_CHECK = False

FIELDS_TO_CHECK = None

def __init__(self, *args, **kwargs):
Expand All @@ -25,14 +30,15 @@ def __init__(self, *args, **kwargs):
reset_state, sender=self.__class__, weak=False,
dispatch_uid='{name}-DirtyFieldsMixin-sweeper'.format(
name=self.__class__.__name__))
if self.ENABLE_M2M_CHECK:
if self.ENABLE_M2M_CHECK or self.ENABLE_BASIC_M2M_CHECK:
self._connect_m2m_relations()
reset_state(sender=self.__class__, instance=self)

def _connect_m2m_relations(self):
m2m_handler = set_m2m_dirty if self.ENABLE_BASIC_M2M_CHECK else reset_state
for m2m_field, model in get_m2m_with_model(self.__class__):
m2m_changed.connect(
reset_state, sender=remote_field(m2m_field).through, weak=False,
m2m_handler, sender=remote_field(m2m_field).through, weak=False,
dispatch_uid='{name}-DirtyFieldsMixin-sweeper-m2m'.format(
name=self.__class__.__name__))

Expand Down Expand Up @@ -121,6 +127,8 @@ def get_dirty_fields(self, check_relationship=False, check_m2m=None, verbose=Fal
return modified_fields

def is_dirty(self, check_relationship=False, check_m2m=None):
if self.ENABLE_BASIC_M2M_CHECK and self._m2m_dirty:
return True
return {} != self.get_dirty_fields(check_relationship=check_relationship,
check_m2m=check_m2m)

Expand Down Expand Up @@ -164,3 +172,9 @@ def reset_state(sender, instance, **kwargs):
instance._original_state = new_state
if instance.ENABLE_M2M_CHECK:
instance._original_m2m_state = instance._as_dict_m2m()
elif instance.ENABLE_BASIC_M2M_CHECK:
instance._m2m_dirty = False


def set_m2m_dirty(sender, instance, **kwargs):
instance._m2m_dirty = True

0 comments on commit d4047f2

Please sign in to comment.