Skip to content

Commit

Permalink
Refs #32948 -- Simplified and optimized Q._combine() and __invert__().
Browse files Browse the repository at this point in the history
- Removed use of Q.deconstruct() in Q._combine().
- Simplified and optimized Q.__invert__() by taking a shallow copy and
  swapping the negated attribute only.
- Simplified construction in Q._combine().
- Simplified conditions in Q._combine() as Q.conditional = True the
  first isinstance() check is unnecessary.
- Removed copy.copy() branch in Q._combine().

Co-authored-by: Keryn Knight <keryn@kerynknight.com>
  • Loading branch information
2 people authored and felixxm committed Jul 27, 2022
1 parent 19b866c commit 845667f
Showing 1 changed file with 6 additions and 11 deletions.
17 changes: 6 additions & 11 deletions django/db/models/query_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
large and/or so that they can be used by other modules without getting into
circular import difficulties.
"""
import copy
import functools
import inspect
import logging
Expand Down Expand Up @@ -54,17 +53,14 @@ def __init__(self, *args, _connector=None, _negated=False, **kwargs):
)

def _combine(self, other, conn):
if not (isinstance(other, Q) or getattr(other, "conditional", False) is True):
if getattr(other, "conditional", False) is False:
raise TypeError(other)

if not self:
return other.copy() if hasattr(other, "copy") else copy.copy(other)
elif isinstance(other, Q) and not other:
_, args, kwargs = self.deconstruct()
return type(self)(*args, **kwargs)
return other.copy()
if not other and isinstance(other, Q):
return self.copy()

obj = type(self)()
obj.connector = conn
obj = self.create(connector=conn)
obj.add(self, conn)
obj.add(other, conn)
return obj
Expand All @@ -79,8 +75,7 @@ def __xor__(self, other):
return self._combine(other, self.XOR)

def __invert__(self):
obj = type(self)()
obj.add(self, self.AND)
obj = self.copy()
obj.negate()
return obj

Expand Down

0 comments on commit 845667f

Please sign in to comment.