Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solve the problem of repeatedly clearing complex nested documents #2565

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions mongoengine/base/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,13 +520,14 @@ def _mark_as_changed(self, key):
if field.startswith(level):
remove(field)

def _clear_changed_fields(self):
def _clear_changed_fields(self, cache_obj=None):
"""Using _get_changed_fields iterate and remove any fields that
are marked as changed.
"""
ReferenceField = _import_class("ReferenceField")
GenericReferenceField = _import_class("GenericReferenceField")

if cache_obj is None:
cache_obj = set()
for changed in self._get_changed_fields():
parts = changed.split(".")
data = self
Expand All @@ -541,7 +542,9 @@ def _clear_changed_fields(self):
else:
field_name = data._reverse_db_field_map.get(part, part)
data = getattr(data, field_name, None)

if id(data) in cache_obj:
continue
cache_obj.add(id(data))
if not isinstance(data, LazyReference) and hasattr(
data, "_changed_fields"
):
Expand All @@ -554,12 +557,12 @@ def _clear_changed_fields(self):
data.field, (ReferenceField, GenericReferenceField)
):
continue
BaseDocument._nestable_types_clear_changed_fields(data)
BaseDocument._nestable_types_clear_changed_fields(data, cache_obj)

self._changed_fields = []

@staticmethod
def _nestable_types_clear_changed_fields(data):
def _nestable_types_clear_changed_fields(data, cache_obj):
"""Inspect nested data for changed fields

:param data: data to inspect for changes
Expand All @@ -577,9 +580,12 @@ def _nestable_types_clear_changed_fields(data):
if hasattr(value, "_get_changed_fields") and not isinstance(
value, Document
): # don't follow references
value._clear_changed_fields()
value._clear_changed_fields(cache_obj)
elif isinstance(value, (list, tuple, dict)):
BaseDocument._nestable_types_clear_changed_fields(value)
if id(data) in cache_obj:
continue
cache_obj.add(id(data))
BaseDocument._nestable_types_clear_changed_fields(value, cache_obj)

@staticmethod
def _nestable_types_changed_fields(changed_fields, base_key, data):
Expand Down