Commits

Anonymous committed 6aab5b9

queryset-refactor: Simplify the way filters are passed to the Query class.

This removes a lot of the complexity for handling exclude() calls and results
in more efficient code. I feel a bit stupid for not having spotted this earlier.

Comments (0)

Files changed (3)

django/db/models/query.py

 from django.conf import settings
 from django.db import connection, transaction, IntegrityError
 from django.db.models.fields import DateField, FieldDoesNotExist
-from django.db.models.query_utils import Q, not_q
+from django.db.models.query_utils import Q
 from django.db.models import signals, sql
 from django.dispatch import dispatcher
 from django.utils.datastructures import SortedDict
         Returns a new QuerySet instance with the args ANDed to the existing
         set.
         """
-        return self._filter_or_exclude(None, *args, **kwargs)
+        return self._filter_or_exclude(False, *args, **kwargs)
 
     def exclude(self, *args, **kwargs):
         """
         Returns a new QuerySet instance with NOT (args) ANDed to the existing
         set.
         """
-        return self._filter_or_exclude(not_q, *args, **kwargs)
+        return self._filter_or_exclude(True, *args, **kwargs)
 
-    def _filter_or_exclude(self, mapper, *args, **kwargs):
-        # mapper is a callable used to transform Q objects,
-        # or None for identity transform.
-        if mapper is None:
-            mapper = lambda x: x
+    def _filter_or_exclude(self, negate, *args, **kwargs):
         if args or kwargs:
             assert self.query.can_filter(), \
-                "Cannot filter a query once a slice has been taken."
+                    "Cannot filter a query once a slice has been taken."
 
         clone = self._clone()
-        if kwargs:
-            clone.query.add_q(mapper(Q(**kwargs)))
-        for arg in args:
-            clone.query.add_q(mapper(arg))
+        if negate:
+            clone.query.add_q(~Q(*args, **kwargs))
+        else:
+            clone.query.add_q(Q(*args, **kwargs))
         return clone
 
     def complex_filter(self, filter_obj):

django/db/models/query_utils.py

     default = AND
 
     def __init__(self, *args, **kwargs):
-        if args and kwargs:
-            raise TypeError('Use positional *or* kwargs; not both!')
-        nodes = list(args) + kwargs.items()
-        super(Q, self).__init__(children=nodes)
+        super(Q, self).__init__(children=list(args) + kwargs.items())
 
     def _combine(self, other, conn):
         if not isinstance(other, Q):
         obj.negate()
         return obj
 
-def not_q(q):
-    return ~q
-

django/db/models/sql/query.py

                 # that's harmless.
                 self.promote_alias(table)
 
-        entry = (alias, col, field, lookup_type, value)
-        if negate and single_filter:
-            # This case is when we're doing the Q2 filter in exclude(Q1, Q2).
-            # It's different from exclude(Q1).exclude(Q2).
-            for node in self.where.children:
-                if getattr(node, 'negated', False):
-                    node.add(entry, connector)
-                    merged = True
-                    break
-        else:
-            self.where.add(entry, connector)
-            merged = False
-
+        self.where.add((alias, col, field, lookup_type, value), connector)
         if negate:
+            self.where.negate()
             for alias in join_list:
                 self.promote_alias(alias)
-            if not merged:
-                self.where.negate()
             if final > 1 and lookup_type != 'isnull':
                 for alias in join_list:
                     if self.alias_map[alias] == self.LOUTER:
                 self.where.start_subtree(connector)
                 self.add_q(child)
                 self.where.end_subtree()
+                if q_object.negated:
+                    self.where.children[-1].negate()
             else:
                 self.add_filter(child, connector, q_object.negated,
                         single_filter=internal)