1+ import threading
12from contextlib import contextmanager
23
34from pymongo .read_concern import ReadConcern
1819)
1920
2021
22+ thread_locals = threading .local ()
23+ thread_locals .no_dereferencing_class = {}
24+
25+
26+ def no_dereferencing_active_for_class (cls ):
27+ return cls in thread_locals .no_dereferencing_class
28+
29+
30+ def _register_no_dereferencing_for_class (cls ):
31+ thread_locals .no_dereferencing_class .setdefault (cls , 0 )
32+ thread_locals .no_dereferencing_class [cls ] += 1
33+
34+
35+ def _unregister_no_dereferencing_for_class (cls ):
36+ thread_locals .no_dereferencing_class [cls ] -= 1
37+ if thread_locals .no_dereferencing_class [cls ] == 0 :
38+ thread_locals .no_dereferencing_class .pop (cls )
39+
40+
2141class switch_db :
2242 """switch_db alias context manager.
2343
@@ -107,7 +127,7 @@ class no_dereference:
107127 Turns off all dereferencing in Documents for the duration of the context
108128 manager::
109129
110- with no_dereference(Group) as Group :
130+ with no_dereference(Group):
111131 Group.objects.find()
112132 """
113133
@@ -130,15 +150,17 @@ def __init__(self, cls):
130150
131151 def __enter__ (self ):
132152 """Change the objects default and _auto_dereference values."""
153+ _register_no_dereferencing_for_class (self .cls )
154+
133155 for field in self .deref_fields :
134156 self .cls ._fields [field ]._auto_dereference = False
135- return self .cls
136157
137158 def __exit__ (self , t , value , traceback ):
138159 """Reset the default and _auto_dereference values."""
160+ _unregister_no_dereferencing_for_class (self .cls )
161+
139162 for field in self .deref_fields :
140163 self .cls ._fields [field ]._auto_dereference = True
141- return self .cls
142164
143165
144166class no_sub_classes :
0 commit comments