summaryrefslogtreecommitdiff
path: root/django/db/models/query_utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'django/db/models/query_utils.py')
-rw-r--r--django/db/models/query_utils.py82
1 files changed, 50 insertions, 32 deletions
diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py
index 188b640850..6ea82b6520 100644
--- a/django/db/models/query_utils.py
+++ b/django/db/models/query_utils.py
@@ -17,7 +17,10 @@ from django.utils import tree
# PathInfo is used when converting lookups (fk__somecol). The contents
# describe the relation in Model terms (model Options and Fields for both
# sides of the relation. The join_field is the field backing the relation.
-PathInfo = namedtuple('PathInfo', 'from_opts to_opts target_fields join_field m2m direct filtered_relation')
+PathInfo = namedtuple(
+ "PathInfo",
+ "from_opts to_opts target_fields join_field m2m direct filtered_relation",
+)
def subclasses(cls):
@@ -31,21 +34,26 @@ class Q(tree.Node):
Encapsulate filters as objects that can then be combined logically (using
`&` and `|`).
"""
+
# Connection types
- AND = 'AND'
- OR = 'OR'
+ AND = "AND"
+ OR = "OR"
default = AND
conditional = True
def __init__(self, *args, _connector=None, _negated=False, **kwargs):
- super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)
+ super().__init__(
+ children=[*args, *sorted(kwargs.items())],
+ connector=_connector,
+ negated=_negated,
+ )
def _combine(self, other, conn):
- if not(isinstance(other, Q) or getattr(other, 'conditional', False) is True):
+ if not (isinstance(other, Q) or getattr(other, "conditional", False) is True):
raise TypeError(other)
if not self:
- return other.copy() if hasattr(other, 'copy') else copy.copy(other)
+ 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)
@@ -68,26 +76,31 @@ class Q(tree.Node):
obj.negate()
return obj
- def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
+ def resolve_expression(
+ self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
+ ):
# We must promote any new joins to left outer joins so that when Q is
# used as an expression, rows aren't filtered due to joins.
clause, joins = query._add_q(
- self, reuse, allow_joins=allow_joins, split_subq=False,
+ self,
+ reuse,
+ allow_joins=allow_joins,
+ split_subq=False,
check_filterable=False,
)
query.promote_joins(joins)
return clause
def deconstruct(self):
- path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
- if path.startswith('django.db.models.query_utils'):
- path = path.replace('django.db.models.query_utils', 'django.db.models')
+ path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
+ if path.startswith("django.db.models.query_utils"):
+ path = path.replace("django.db.models.query_utils", "django.db.models")
args = tuple(self.children)
kwargs = {}
if self.connector != self.default:
- kwargs['_connector'] = self.connector
+ kwargs["_connector"] = self.connector
if self.negated:
- kwargs['_negated'] = True
+ kwargs["_negated"] = True
return path, args, kwargs
@@ -96,6 +109,7 @@ class DeferredAttribute:
A wrapper for a deferred-loading field. When the value is read from this
object the first time, the query is executed.
"""
+
def __init__(self, field):
self.field = field
@@ -132,7 +146,6 @@ class DeferredAttribute:
class RegisterLookupMixin:
-
@classmethod
def _get_lookup(cls, lookup_name):
return cls.get_lookups().get(lookup_name, None)
@@ -140,13 +153,16 @@ class RegisterLookupMixin:
@classmethod
@functools.lru_cache(maxsize=None)
def get_lookups(cls):
- class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
+ class_lookups = [
+ parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls)
+ ]
return cls.merge_dicts(class_lookups)
def get_lookup(self, lookup_name):
from django.db.models.lookups import Lookup
+
found = self._get_lookup(lookup_name)
- if found is None and hasattr(self, 'output_field'):
+ if found is None and hasattr(self, "output_field"):
return self.output_field.get_lookup(lookup_name)
if found is not None and not issubclass(found, Lookup):
return None
@@ -154,8 +170,9 @@ class RegisterLookupMixin:
def get_transform(self, lookup_name):
from django.db.models.lookups import Transform
+
found = self._get_lookup(lookup_name)
- if found is None and hasattr(self, 'output_field'):
+ if found is None and hasattr(self, "output_field"):
return self.output_field.get_transform(lookup_name)
if found is not None and not issubclass(found, Transform):
return None
@@ -181,7 +198,7 @@ class RegisterLookupMixin:
def register_lookup(cls, lookup, lookup_name=None):
if lookup_name is None:
lookup_name = lookup.lookup_name
- if 'class_lookups' not in cls.__dict__:
+ if "class_lookups" not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup_name] = lookup
cls._clear_cached_lookups()
@@ -228,8 +245,8 @@ def select_related_descend(field, restricted, requested, load_fields, reverse=Fa
if field.attname not in load_fields:
if restricted and field.name in requested:
msg = (
- 'Field %s.%s cannot be both deferred and traversed using '
- 'select_related at the same time.'
+ "Field %s.%s cannot be both deferred and traversed using "
+ "select_related at the same time."
) % (field.model._meta.object_name, field.name)
raise FieldError(msg)
return True
@@ -255,12 +272,14 @@ def check_rel_lookup_compatibility(model, target_opts, field):
1) model and opts match (where proxy inheritance is removed)
2) model is parent of opts' model or the other way around
"""
+
def check(opts):
return (
- model._meta.concrete_model == opts.concrete_model or
- opts.concrete_model in model._meta.get_parent_list() or
- model in opts.get_parent_list()
+ model._meta.concrete_model == opts.concrete_model
+ or opts.concrete_model in model._meta.get_parent_list()
+ or model in opts.get_parent_list()
)
+
# If the field is a primary key, then doing a query against the field's
# model is ok, too. Consider the case:
# class Restaurant(models.Model):
@@ -270,9 +289,8 @@ def check_rel_lookup_compatibility(model, target_opts, field):
# give Place's opts as the target opts, but Restaurant isn't compatible
# with that. This logic applies only to primary keys, as when doing __in=qs,
# we are going to turn this into __in=qs.values('pk') later on.
- return (
- check(target_opts) or
- (getattr(field, 'primary_key', False) and check(field.model._meta))
+ return check(target_opts) or (
+ getattr(field, "primary_key", False) and check(field.model._meta)
)
@@ -281,11 +299,11 @@ class FilteredRelation:
def __init__(self, relation_name, *, condition=Q()):
if not relation_name:
- raise ValueError('relation_name cannot be empty.')
+ raise ValueError("relation_name cannot be empty.")
self.relation_name = relation_name
self.alias = None
if not isinstance(condition, Q):
- raise ValueError('condition argument must be a Q() instance.')
+ raise ValueError("condition argument must be a Q() instance.")
self.condition = condition
self.path = []
@@ -293,9 +311,9 @@ class FilteredRelation:
if not isinstance(other, self.__class__):
return NotImplemented
return (
- self.relation_name == other.relation_name and
- self.alias == other.alias and
- self.condition == other.condition
+ self.relation_name == other.relation_name
+ and self.alias == other.alias
+ and self.condition == other.condition
)
def clone(self):
@@ -309,7 +327,7 @@ class FilteredRelation:
QuerySet.annotate() only accepts expression-like arguments
(with a resolve_expression() method).
"""
- raise NotImplementedError('FilteredRelation.resolve_expression() is unused.')
+ raise NotImplementedError("FilteredRelation.resolve_expression() is unused.")
def as_sql(self, compiler, connection):
# Resolve the condition in Join.filtered_relation.