From 8199c3daa273ce80069ad2167833d8cdd6b0200e Mon Sep 17 00:00:00 2001 From: Rich Rauenzahn Date: Wed, 10 May 2023 16:56:17 -0700 Subject: [PATCH] Replace a deepcopy of the Q object custom deep copy --- polymorphic/query_translate.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/polymorphic/query_translate.py b/polymorphic/query_translate.py index 2974f4cb..65d6137b 100644 --- a/polymorphic/query_translate.py +++ b/polymorphic/query_translate.py @@ -81,6 +81,28 @@ def tree_node_correct_field_specs(my_model, node): return potential_q_object +def _deepcopy_q_object(q): + """ + Make a deepcopy of a Q-object. + """ + def _copy_child(child): + if isinstance(child, tuple): + return child # tuples are immutable, no need to make a copy. + elif isinstance(child, Q): + return _deepcopy_q_object(child) + else: + raise RuntimeError("Unknown child type: %s", type(child)) + + children = [_copy_child(c) for c in q.children] + + if hasattr(q, 'copy'): # Django 4.2+ + obj = q.copy() + obj.children = children + else: + obj = Q(*children, _connector=q.connector, _negated=q.negated) + return obj + + def translate_polymorphic_filter_definitions_in_args(queryset_model, args, using=DEFAULT_DB_ALIAS): """ Translate the non-keyword argument list for PolymorphicQuerySet.filter() @@ -93,7 +115,7 @@ def translate_polymorphic_filter_definitions_in_args(queryset_model, args, using Returns: modified Q objects """ return [ - translate_polymorphic_Q_object(queryset_model, copy.deepcopy(q), using=using) for q in args + translate_polymorphic_Q_object(queryset_model, _deepcopy_q_object(q), using=using) for q in args ]