1717from mongoengine .common import _import_class
1818from mongoengine .connection import get_db
1919from mongoengine .context_managers import (
20+ no_dereferencing_active_for_class ,
2021 set_read_write_concern ,
2122 set_write_concern ,
2223 switch_db ,
@@ -51,9 +52,6 @@ class BaseQuerySet:
5152 providing :class:`~mongoengine.Document` objects as the results.
5253 """
5354
54- __dereference = False
55- _auto_dereference = True
56-
5755 def __init__ (self , document , collection ):
5856 self ._document = document
5957 self ._collection_obj = collection
@@ -74,6 +72,9 @@ def __init__(self, document, collection):
7472 self ._as_pymongo = False
7573 self ._search_text = None
7674
75+ self .__dereference = False
76+ self .__auto_dereference = True
77+
7778 # If inheritance is allowed, only return instances and instances of
7879 # subclasses of the class being used
7980 if document ._meta .get ("allow_inheritance" ) is True :
@@ -795,7 +796,7 @@ def clone(self):
795796 return self ._clone_into (self .__class__ (self ._document , self ._collection_obj ))
796797
797798 def _clone_into (self , new_qs ):
798- """Copy all of the relevant properties of this queryset to
799+ """Copy all the relevant properties of this queryset to
799800 a new queryset (which has to be an instance of
800801 :class:`~mongoengine.queryset.base.BaseQuerySet`).
801802 """
@@ -825,7 +826,6 @@ def _clone_into(self, new_qs):
825826 "_empty" ,
826827 "_hint" ,
827828 "_collation" ,
828- "_auto_dereference" ,
829829 "_search_text" ,
830830 "_max_time_ms" ,
831831 "_comment" ,
@@ -836,6 +836,8 @@ def _clone_into(self, new_qs):
836836 val = getattr (self , prop )
837837 setattr (new_qs , prop , copy .copy (val ))
838838
839+ new_qs .__auto_dereference = self ._BaseQuerySet__auto_dereference
840+
839841 if self ._cursor_obj :
840842 new_qs ._cursor_obj = self ._cursor_obj .clone ()
841843
@@ -1741,10 +1743,15 @@ def _dereference(self):
17411743 self .__dereference = _import_class ("DeReference" )()
17421744 return self .__dereference
17431745
1746+ @property
1747+ def _auto_dereference (self ):
1748+ should_deref = not no_dereferencing_active_for_class (self ._document )
1749+ return should_deref and self .__auto_dereference
1750+
17441751 def no_dereference (self ):
17451752 """Turn off any dereferencing for the results of this queryset."""
17461753 queryset = self .clone ()
1747- queryset ._auto_dereference = False
1754+ queryset .__auto_dereference = False
17481755 return queryset
17491756
17501757 # Helper Functions
0 commit comments