Refs -- Simplified and optimized Q._combine() and __invert__().

- 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>
This commit is contained in:
Nick Pope 2021-07-20 16:28:25 +01:00 committed by Mariusz Felisiak
parent 19b866c254
commit 845667f2d1
1 changed files with 6 additions and 11 deletions
django/db/models

View File

@ -5,7 +5,6 @@ Factored out from django.db.models.query to avoid making the main module very
large and/or so that they can be used by other modules without getting into large and/or so that they can be used by other modules without getting into
circular import difficulties. circular import difficulties.
""" """
import copy
import functools import functools
import inspect import inspect
import logging import logging
@ -54,17 +53,14 @@ class Q(tree.Node):
) )
def _combine(self, other, conn): 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) raise TypeError(other)
if not self: if not self:
return other.copy() if hasattr(other, "copy") else copy.copy(other) return other.copy()
elif isinstance(other, Q) and not other: if not other and isinstance(other, Q):
_, args, kwargs = self.deconstruct() return self.copy()
return type(self)(*args, **kwargs)
obj = type(self)() obj = self.create(connector=conn)
obj.connector = conn
obj.add(self, conn) obj.add(self, conn)
obj.add(other, conn) obj.add(other, conn)
return obj return obj
@ -79,8 +75,7 @@ class Q(tree.Node):
return self._combine(other, self.XOR) return self._combine(other, self.XOR)
def __invert__(self): def __invert__(self):
obj = type(self)() obj = self.copy()
obj.add(self, self.AND)
obj.negate() obj.negate()
return obj return obj