/django/db/models/query_utils.py

http://github.com/django/django · Python · 351 lines · 229 code · 41 blank · 81 comment · 36 complexity · ae8ed6206b3f2a002f53ea2126343c92 MD5 · raw file

  1. """
  2. Various data structures used in query construction.
  3. Factored out from django.db.models.query to avoid making the main module very
  4. large and/or so that they can be used by other modules without getting into
  5. circular import difficulties.
  6. """
  7. import copy
  8. import functools
  9. import inspect
  10. import warnings
  11. from collections import namedtuple
  12. from django.core.exceptions import FieldDoesNotExist, FieldError
  13. from django.db.models.constants import LOOKUP_SEP
  14. from django.utils import tree
  15. from django.utils.deprecation import RemovedInDjango40Warning
  16. # PathInfo is used when converting lookups (fk__somecol). The contents
  17. # describe the relation in Model terms (model Options and Fields for both
  18. # sides of the relation. The join_field is the field backing the relation.
  19. PathInfo = namedtuple('PathInfo', 'from_opts to_opts target_fields join_field m2m direct filtered_relation')
  20. class InvalidQueryType(type):
  21. @property
  22. def _subclasses(self):
  23. return (FieldDoesNotExist, FieldError)
  24. def __warn(self):
  25. warnings.warn(
  26. 'The InvalidQuery exception class is deprecated. Use '
  27. 'FieldDoesNotExist or FieldError instead.',
  28. category=RemovedInDjango40Warning,
  29. stacklevel=4,
  30. )
  31. def __instancecheck__(self, instance):
  32. self.__warn()
  33. return isinstance(instance, self._subclasses) or super().__instancecheck__(instance)
  34. def __subclasscheck__(self, subclass):
  35. self.__warn()
  36. return issubclass(subclass, self._subclasses) or super().__subclasscheck__(subclass)
  37. class InvalidQuery(Exception, metaclass=InvalidQueryType):
  38. pass
  39. def subclasses(cls):
  40. yield cls
  41. for subclass in cls.__subclasses__():
  42. yield from subclasses(subclass)
  43. class Q(tree.Node):
  44. """
  45. Encapsulate filters as objects that can then be combined logically (using
  46. `&` and `|`).
  47. """
  48. # Connection types
  49. AND = 'AND'
  50. OR = 'OR'
  51. default = AND
  52. conditional = True
  53. def __init__(self, *args, _connector=None, _negated=False, **kwargs):
  54. super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)
  55. def _combine(self, other, conn):
  56. if not isinstance(other, Q):
  57. raise TypeError(other)
  58. # If the other Q() is empty, ignore it and just use `self`.
  59. if not other:
  60. return copy.deepcopy(self)
  61. # Or if this Q is empty, ignore it and just use `other`.
  62. elif not self:
  63. return copy.deepcopy(other)
  64. obj = type(self)()
  65. obj.connector = conn
  66. obj.add(self, conn)
  67. obj.add(other, conn)
  68. return obj
  69. def __or__(self, other):
  70. return self._combine(other, self.OR)
  71. def __and__(self, other):
  72. return self._combine(other, self.AND)
  73. def __invert__(self):
  74. obj = type(self)()
  75. obj.add(self, self.AND)
  76. obj.negate()
  77. return obj
  78. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  79. # We must promote any new joins to left outer joins so that when Q is
  80. # used as an expression, rows aren't filtered due to joins.
  81. clause, joins = query._add_q(
  82. self, reuse, allow_joins=allow_joins, split_subq=False,
  83. check_filterable=False,
  84. )
  85. query.promote_joins(joins)
  86. return clause
  87. def deconstruct(self):
  88. path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  89. if path.startswith('django.db.models.query_utils'):
  90. path = path.replace('django.db.models.query_utils', 'django.db.models')
  91. args, kwargs = (), {}
  92. if len(self.children) == 1 and not isinstance(self.children[0], Q):
  93. child = self.children[0]
  94. kwargs = {child[0]: child[1]}
  95. else:
  96. args = tuple(self.children)
  97. if self.connector != self.default:
  98. kwargs = {'_connector': self.connector}
  99. if self.negated:
  100. kwargs['_negated'] = True
  101. return path, args, kwargs
  102. class DeferredAttribute:
  103. """
  104. A wrapper for a deferred-loading field. When the value is read from this
  105. object the first time, the query is executed.
  106. """
  107. def __init__(self, field):
  108. self.field = field
  109. def __get__(self, instance, cls=None):
  110. """
  111. Retrieve and caches the value from the datastore on the first lookup.
  112. Return the cached value.
  113. """
  114. if instance is None:
  115. return self
  116. data = instance.__dict__
  117. field_name = self.field.attname
  118. if field_name not in data:
  119. # Let's see if the field is part of the parent chain. If so we
  120. # might be able to reuse the already loaded value. Refs #18343.
  121. val = self._check_parent_chain(instance)
  122. if val is None:
  123. instance.refresh_from_db(fields=[field_name])
  124. val = getattr(instance, field_name)
  125. data[field_name] = val
  126. return data[field_name]
  127. def _check_parent_chain(self, instance):
  128. """
  129. Check if the field value can be fetched from a parent field already
  130. loaded in the instance. This can be done if the to-be fetched
  131. field is a primary key field.
  132. """
  133. opts = instance._meta
  134. link_field = opts.get_ancestor_link(self.field.model)
  135. if self.field.primary_key and self.field != link_field:
  136. return getattr(instance, link_field.attname)
  137. return None
  138. class RegisterLookupMixin:
  139. @classmethod
  140. def _get_lookup(cls, lookup_name):
  141. return cls.get_lookups().get(lookup_name, None)
  142. @classmethod
  143. @functools.lru_cache(maxsize=None)
  144. def get_lookups(cls):
  145. class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
  146. return cls.merge_dicts(class_lookups)
  147. def get_lookup(self, lookup_name):
  148. from django.db.models.lookups import Lookup
  149. found = self._get_lookup(lookup_name)
  150. if found is None and hasattr(self, 'output_field'):
  151. return self.output_field.get_lookup(lookup_name)
  152. if found is not None and not issubclass(found, Lookup):
  153. return None
  154. return found
  155. def get_transform(self, lookup_name):
  156. from django.db.models.lookups import Transform
  157. found = self._get_lookup(lookup_name)
  158. if found is None and hasattr(self, 'output_field'):
  159. return self.output_field.get_transform(lookup_name)
  160. if found is not None and not issubclass(found, Transform):
  161. return None
  162. return found
  163. @staticmethod
  164. def merge_dicts(dicts):
  165. """
  166. Merge dicts in reverse to preference the order of the original list. e.g.,
  167. merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
  168. """
  169. merged = {}
  170. for d in reversed(dicts):
  171. merged.update(d)
  172. return merged
  173. @classmethod
  174. def _clear_cached_lookups(cls):
  175. for subclass in subclasses(cls):
  176. subclass.get_lookups.cache_clear()
  177. @classmethod
  178. def register_lookup(cls, lookup, lookup_name=None):
  179. if lookup_name is None:
  180. lookup_name = lookup.lookup_name
  181. if 'class_lookups' not in cls.__dict__:
  182. cls.class_lookups = {}
  183. cls.class_lookups[lookup_name] = lookup
  184. cls._clear_cached_lookups()
  185. return lookup
  186. @classmethod
  187. def _unregister_lookup(cls, lookup, lookup_name=None):
  188. """
  189. Remove given lookup from cls lookups. For use in tests only as it's
  190. not thread-safe.
  191. """
  192. if lookup_name is None:
  193. lookup_name = lookup.lookup_name
  194. del cls.class_lookups[lookup_name]
  195. def select_related_descend(field, restricted, requested, load_fields, reverse=False):
  196. """
  197. Return True if this field should be used to descend deeper for
  198. select_related() purposes. Used by both the query construction code
  199. (sql.query.fill_related_selections()) and the model instance creation code
  200. (query.get_klass_info()).
  201. Arguments:
  202. * field - the field to be checked
  203. * restricted - a boolean field, indicating if the field list has been
  204. manually restricted using a requested clause)
  205. * requested - The select_related() dictionary.
  206. * load_fields - the set of fields to be loaded on this model
  207. * reverse - boolean, True if we are checking a reverse select related
  208. """
  209. if not field.remote_field:
  210. return False
  211. if field.remote_field.parent_link and not reverse:
  212. return False
  213. if restricted:
  214. if reverse and field.related_query_name() not in requested:
  215. return False
  216. if not reverse and field.name not in requested:
  217. return False
  218. if not restricted and field.null:
  219. return False
  220. if load_fields:
  221. if field.attname not in load_fields:
  222. if restricted and field.name in requested:
  223. msg = (
  224. 'Field %s.%s cannot be both deferred and traversed using '
  225. 'select_related at the same time.'
  226. ) % (field.model._meta.object_name, field.name)
  227. raise FieldError(msg)
  228. return True
  229. def refs_expression(lookup_parts, annotations):
  230. """
  231. Check if the lookup_parts contains references to the given annotations set.
  232. Because the LOOKUP_SEP is contained in the default annotation names, check
  233. each prefix of the lookup_parts for a match.
  234. """
  235. for n in range(1, len(lookup_parts) + 1):
  236. level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
  237. if level_n_lookup in annotations and annotations[level_n_lookup]:
  238. return annotations[level_n_lookup], lookup_parts[n:]
  239. return False, ()
  240. def check_rel_lookup_compatibility(model, target_opts, field):
  241. """
  242. Check that self.model is compatible with target_opts. Compatibility
  243. is OK if:
  244. 1) model and opts match (where proxy inheritance is removed)
  245. 2) model is parent of opts' model or the other way around
  246. """
  247. def check(opts):
  248. return (
  249. model._meta.concrete_model == opts.concrete_model or
  250. opts.concrete_model in model._meta.get_parent_list() or
  251. model in opts.get_parent_list()
  252. )
  253. # If the field is a primary key, then doing a query against the field's
  254. # model is ok, too. Consider the case:
  255. # class Restaurant(models.Model):
  256. # place = OneToOneField(Place, primary_key=True):
  257. # Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
  258. # If we didn't have the primary key check, then pk__in (== place__in) would
  259. # give Place's opts as the target opts, but Restaurant isn't compatible
  260. # with that. This logic applies only to primary keys, as when doing __in=qs,
  261. # we are going to turn this into __in=qs.values('pk') later on.
  262. return (
  263. check(target_opts) or
  264. (getattr(field, 'primary_key', False) and check(field.model._meta))
  265. )
  266. class FilteredRelation:
  267. """Specify custom filtering in the ON clause of SQL joins."""
  268. def __init__(self, relation_name, *, condition=Q()):
  269. if not relation_name:
  270. raise ValueError('relation_name cannot be empty.')
  271. self.relation_name = relation_name
  272. self.alias = None
  273. if not isinstance(condition, Q):
  274. raise ValueError('condition argument must be a Q() instance.')
  275. self.condition = condition
  276. self.path = []
  277. def __eq__(self, other):
  278. if not isinstance(other, self.__class__):
  279. return NotImplemented
  280. return (
  281. self.relation_name == other.relation_name and
  282. self.alias == other.alias and
  283. self.condition == other.condition
  284. )
  285. def clone(self):
  286. clone = FilteredRelation(self.relation_name, condition=self.condition)
  287. clone.alias = self.alias
  288. clone.path = self.path[:]
  289. return clone
  290. def resolve_expression(self, *args, **kwargs):
  291. """
  292. QuerySet.annotate() only accepts expression-like arguments
  293. (with a resolve_expression() method).
  294. """
  295. raise NotImplementedError('FilteredRelation.resolve_expression() is unused.')
  296. def as_sql(self, compiler, connection):
  297. # Resolve the condition in Join.filtered_relation.
  298. query = compiler.query
  299. where = query.build_filtered_relation_q(self.condition, reuse=set(self.path))
  300. return compiler.compile(where)