Skip to content

Commit

Permalink
Replace deepcopy of the Q object jazzband#543
Browse files Browse the repository at this point in the history
  • Loading branch information
j-antunes committed Nov 14, 2023
1 parent 4711968 commit d7b2613
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions polymorphic/query_translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ def translate_polymorphic_filter_definitions_in_kwargs(
"""
additional_args = []
for field_path, val in kwargs.copy().items(): # Python 3 needs copy

new_expr = _translate_polymorphic_filter_definition(
queryset_model, field_path, val, using=using
)
Expand Down Expand Up @@ -81,6 +80,29 @@ 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()
Expand All @@ -93,7 +115,8 @@ 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
]


Expand Down

0 comments on commit d7b2613

Please sign in to comment.