query_utils.py 12 KB

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