From 88642eb0212d276eaa4efe0d605fc3af743158a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9=20Perez?= Date: Tue, 23 Mar 2021 22:11:41 +0100 Subject: [PATCH] Fix deepcopy on EmbeddedDocument --- AUTHORS | 1 + docs/changelog.rst | 1 + mongoengine/document.py | 9 +++++++++ tests/document/test_instance.py | 9 +++++++++ 4 files changed, 20 insertions(+) diff --git a/AUTHORS b/AUTHORS index 0c7f6b46..64069d33 100644 --- a/AUTHORS +++ b/AUTHORS @@ -260,3 +260,4 @@ that much better: * Stankiewicz Mateusz (https://github.com/mas15) * Felix Schultheiß (https://github.com/felix-smashdocs) * Jan Stein (https://github.com/janste63) + * Timothé Perez (https://github.com/AchilleAsh) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3f4252a5..737ec043 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -13,6 +13,7 @@ Changes in 0.23.1 =========== - Bug fix: ignore LazyReferenceFields when clearing _changed_fields #2484 - Improve connection doc #2481 +- Fix deepcopy on EmbeddedDocument Changes in 0.23.0 ================= diff --git a/mongoengine/document.py b/mongoengine/document.py index 0ba5db12..9be49368 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -99,6 +99,15 @@ class EmbeddedDocument(BaseDocument, metaclass=DocumentMetaclass): def __ne__(self, other): return not self.__eq__(other) + def __getstate__(self): + data = super().__getstate__() + data["_instance"] = self._instance + return data + + def __setstate__(self, state): + super().__setstate__(state) + self._instance = state["_instance"] + def to_mongo(self, *args, **kwargs): data = super().to_mongo(*args, **kwargs) diff --git a/tests/document/test_instance.py b/tests/document/test_instance.py index 1469c9bb..77d51a46 100644 --- a/tests/document/test_instance.py +++ b/tests/document/test_instance.py @@ -3,6 +3,7 @@ import pickle import unittest import uuid import weakref +from copy import deepcopy from datetime import datetime import bson @@ -78,6 +79,14 @@ class TestDocumentInstance(MongoDBTestCase): else: assert field._instance == instance + def test_deepcopy(self): + """Ensure that the _instance attribute on EmbeddedDocument exists after a deepcopy""" + + doc = self.Job() + assert doc._instance is None + copied = deepcopy(doc) + assert copied._instance is None + def test_capped_collection(self): """Ensure that capped collections work properly."""