query_utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 functools
  8. import inspect
  9. import logging
  10. from collections import namedtuple
  11. from django.core.exceptions import FieldError
  12. from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections
  13. from django.db.models.constants import LOOKUP_SEP
  14. from django.utils import tree
  15. logger = logging.getLogger("django.db.models")
  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(
  20. "PathInfo",
  21. "from_opts to_opts target_fields join_field m2m direct filtered_relation",
  22. )
  23. def subclasses(cls):
  24. yield cls
  25. for subclass in cls.__subclasses__():
  26. yield from subclasses(subclass)
  27. class Q(tree.Node):
  28. """
  29. Encapsulate filters as objects that can then be combined logically (using
  30. `&` and `|`).
  31. """
  32. # Connection types
  33. AND = "AND"
  34. OR = "OR"
  35. XOR = "XOR"
  36. default = AND
  37. conditional = True
  38. connectors = (None, AND, OR, XOR)
  39. def __init__(self, *args, _connector=None, _negated=False, **kwargs):
  40. if _connector not in self.connectors:
  41. connector_reprs = ", ".join(f"{conn!r}" for conn in self.connectors[1:])
  42. raise ValueError(f"_connector must be one of {connector_reprs}, or None.")
  43. super().__init__(
  44. children=[*args, *sorted(kwargs.items())],
  45. connector=_connector,
  46. negated=_negated,
  47. )
  48. def _combine(self, other, conn):
  49. if getattr(other, "conditional", False) is False:
  50. raise TypeError(other)
  51. if not self:
  52. return other.copy()
  53. if not other and isinstance(other, Q):
  54. return self.copy()
  55. obj = self.create(connector=conn)
  56. obj.add(self, conn)
  57. obj.add(other, conn)
  58. return obj
  59. def __or__(self, other):
  60. return self._combine(other, self.OR)
  61. def __and__(self, other):
  62. return self._combine(other, self.AND)
  63. def __xor__(self, other):
  64. return self._combine(other, self.XOR)
  65. def __invert__(self):
  66. obj = self.copy()
  67. obj.negate()
  68. return obj
  69. def resolve_expression(
  70. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  71. ):
  72. # We must promote any new joins to left outer joins so that when Q is
  73. # used as an expression, rows aren't filtered due to joins.
  74. clause, joins = query._add_q(
  75. self,
  76. reuse,
  77. allow_joins=allow_joins,
  78. split_subq=False,
  79. check_filterable=False,
  80. summarize=summarize,
  81. )
  82. query.promote_joins(joins)
  83. return clause
  84. def flatten(self):
  85. """
  86. Recursively yield this Q object and all subexpressions, in depth-first
  87. order.
  88. """
  89. yield self
  90. for child in self.children:
  91. if isinstance(child, tuple):
  92. # Use the lookup.
  93. child = child[1]
  94. if hasattr(child, "flatten"):
  95. yield from child.flatten()
  96. else:
  97. yield child
  98. def check(self, against, using=DEFAULT_DB_ALIAS):
  99. """
  100. Do a database query to check if the expressions of the Q instance
  101. matches against the expressions.
  102. """
  103. # Avoid circular imports.
  104. from django.db.models import BooleanField, Value
  105. from django.db.models.functions import Coalesce
  106. from django.db.models.sql import Query
  107. from django.db.models.sql.constants import SINGLE
  108. query = Query(None)
  109. for name, value in against.items():
  110. if not hasattr(value, "resolve_expression"):
  111. value = Value(value)
  112. query.add_annotation(value, name, select=False)
  113. query.add_annotation(Value(1), "_check")
  114. # This will raise a FieldError if a field is missing in "against".
  115. if connections[using].features.supports_comparing_boolean_expr:
  116. query.add_q(Q(Coalesce(self, True, output_field=BooleanField())))
  117. else:
  118. query.add_q(self)
  119. compiler = query.get_compiler(using=using)
  120. try:
  121. return compiler.execute_sql(SINGLE) is not None
  122. except DatabaseError as e:
  123. logger.warning("Got a database error calling check() on %r: %s", self, e)
  124. return True
  125. def deconstruct(self):
  126. path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
  127. if path.startswith("django.db.models.query_utils"):
  128. path = path.replace("django.db.models.query_utils", "django.db.models")
  129. args = tuple(self.children)
  130. kwargs = {}
  131. if self.connector != self.default:
  132. kwargs["_connector"] = self.connector
  133. if self.negated:
  134. kwargs["_negated"] = True
  135. return path, args, kwargs
  136. class DeferredAttribute:
  137. """
  138. A wrapper for a deferred-loading field. When the value is read from this
  139. object the first time, the query is executed.
  140. """
  141. def __init__(self, field):
  142. self.field = field
  143. def __get__(self, instance, cls=None):
  144. """
  145. Retrieve and caches the value from the datastore on the first lookup.
  146. Return the cached value.
  147. """
  148. if instance is None:
  149. return self
  150. data = instance.__dict__
  151. field_name = self.field.attname
  152. if field_name not in data:
  153. # Let's see if the field is part of the parent chain. If so we
  154. # might be able to reuse the already loaded value. Refs #18343.
  155. val = self._check_parent_chain(instance)
  156. if val is None:
  157. instance.refresh_from_db(fields=[field_name])
  158. else:
  159. data[field_name] = val
  160. return data[field_name]
  161. def _check_parent_chain(self, instance):
  162. """
  163. Check if the field value can be fetched from a parent field already
  164. loaded in the instance. This can be done if the to-be fetched
  165. field is a primary key field.
  166. """
  167. opts = instance._meta
  168. link_field = opts.get_ancestor_link(self.field.model)
  169. if self.field.primary_key and self.field != link_field:
  170. return getattr(instance, link_field.attname)
  171. return None
  172. class class_or_instance_method:
  173. """
  174. Hook used in RegisterLookupMixin to return partial functions depending on
  175. the caller type (instance or class of models.Field).
  176. """
  177. def __init__(self, class_method, instance_method):
  178. self.class_method = class_method
  179. self.instance_method = instance_method
  180. def __get__(self, instance, owner):
  181. if instance is None:
  182. return functools.partial(self.class_method, owner)
  183. return functools.partial(self.instance_method, instance)
  184. class RegisterLookupMixin:
  185. def _get_lookup(self, lookup_name):
  186. return self.get_lookups().get(lookup_name, None)
  187. @functools.lru_cache(maxsize=None)
  188. def get_class_lookups(cls):
  189. class_lookups = [
  190. parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls)
  191. ]
  192. return cls.merge_dicts(class_lookups)
  193. def get_instance_lookups(self):
  194. class_lookups = self.get_class_lookups()
  195. if instance_lookups := getattr(self, "instance_lookups", None):
  196. return {**class_lookups, **instance_lookups}
  197. return class_lookups
  198. get_lookups = class_or_instance_method(get_class_lookups, get_instance_lookups)
  199. get_class_lookups = classmethod(get_class_lookups)
  200. def get_lookup(self, lookup_name):
  201. from django.db.models.lookups import Lookup
  202. found = self._get_lookup(lookup_name)
  203. if found is None and hasattr(self, "output_field"):
  204. return self.output_field.get_lookup(lookup_name)
  205. if found is not None and not issubclass(found, Lookup):
  206. return None
  207. return found
  208. def get_transform(self, lookup_name):
  209. from django.db.models.lookups import Transform
  210. found = self._get_lookup(lookup_name)
  211. if found is None and hasattr(self, "output_field"):
  212. return self.output_field.get_transform(lookup_name)
  213. if found is not None and not issubclass(found, Transform):
  214. return None
  215. return found
  216. @staticmethod
  217. def merge_dicts(dicts):
  218. """
  219. Merge dicts in reverse to preference the order of the original list. e.g.,
  220. merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
  221. """
  222. merged = {}
  223. for d in reversed(dicts):
  224. merged.update(d)
  225. return merged
  226. @classmethod
  227. def _clear_cached_class_lookups(cls):
  228. for subclass in subclasses(cls):
  229. subclass.get_class_lookups.cache_clear()
  230. def register_class_lookup(cls, lookup, lookup_name=None):
  231. if lookup_name is None:
  232. lookup_name = lookup.lookup_name
  233. if "class_lookups" not in cls.__dict__:
  234. cls.class_lookups = {}
  235. cls.class_lookups[lookup_name] = lookup
  236. cls._clear_cached_class_lookups()
  237. return lookup
  238. def register_instance_lookup(self, lookup, lookup_name=None):
  239. if lookup_name is None:
  240. lookup_name = lookup.lookup_name
  241. if "instance_lookups" not in self.__dict__:
  242. self.instance_lookups = {}
  243. self.instance_lookups[lookup_name] = lookup
  244. return lookup
  245. register_lookup = class_or_instance_method(
  246. register_class_lookup, register_instance_lookup
  247. )
  248. register_class_lookup = classmethod(register_class_lookup)
  249. def _unregister_class_lookup(cls, lookup, lookup_name=None):
  250. """
  251. Remove given lookup from cls lookups. For use in tests only as it's
  252. not thread-safe.
  253. """
  254. if lookup_name is None:
  255. lookup_name = lookup.lookup_name
  256. del cls.class_lookups[lookup_name]
  257. cls._clear_cached_class_lookups()
  258. def _unregister_instance_lookup(self, lookup, lookup_name=None):
  259. """
  260. Remove given lookup from instance lookups. For use in tests only as
  261. it's not thread-safe.
  262. """
  263. if lookup_name is None:
  264. lookup_name = lookup.lookup_name
  265. del self.instance_lookups[lookup_name]
  266. _unregister_lookup = class_or_instance_method(
  267. _unregister_class_lookup, _unregister_instance_lookup
  268. )
  269. _unregister_class_lookup = classmethod(_unregister_class_lookup)
  270. def select_related_descend(field, restricted, requested, select_mask, reverse=False):
  271. """
  272. Return True if this field should be used to descend deeper for
  273. select_related() purposes. Used by both the query construction code
  274. (compiler.get_related_selections()) and the model instance creation code
  275. (compiler.klass_info).
  276. Arguments:
  277. * field - the field to be checked
  278. * restricted - a boolean field, indicating if the field list has been
  279. manually restricted using a requested clause)
  280. * requested - The select_related() dictionary.
  281. * select_mask - the dictionary of selected fields.
  282. * reverse - boolean, True if we are checking a reverse select related
  283. """
  284. if not field.remote_field:
  285. return False
  286. if field.remote_field.parent_link and not reverse:
  287. return False
  288. if restricted:
  289. if reverse and field.related_query_name() not in requested:
  290. return False
  291. if not reverse and field.name not in requested:
  292. return False
  293. if not restricted and field.null:
  294. return False
  295. if (
  296. restricted
  297. and select_mask
  298. and field.name in requested
  299. and field not in select_mask
  300. ):
  301. raise FieldError(
  302. f"Field {field.model._meta.object_name}.{field.name} cannot be both "
  303. "deferred and traversed using select_related at the same time."
  304. )
  305. return True
  306. def refs_expression(lookup_parts, annotations):
  307. """
  308. Check if the lookup_parts contains references to the given annotations set.
  309. Because the LOOKUP_SEP is contained in the default annotation names, check
  310. each prefix of the lookup_parts for a match.
  311. """
  312. for n in range(1, len(lookup_parts) + 1):
  313. level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
  314. if annotations.get(level_n_lookup):
  315. return level_n_lookup, lookup_parts[n:]
  316. return None, ()
  317. def check_rel_lookup_compatibility(model, target_opts, field):
  318. """
  319. Check that self.model is compatible with target_opts. Compatibility
  320. is OK if:
  321. 1) model and opts match (where proxy inheritance is removed)
  322. 2) model is parent of opts' model or the other way around
  323. """
  324. def check(opts):
  325. return (
  326. model._meta.concrete_model == opts.concrete_model
  327. or opts.concrete_model in model._meta.get_parent_list()
  328. or model in opts.get_parent_list()
  329. )
  330. # If the field is a primary key, then doing a query against the field's
  331. # model is ok, too. Consider the case:
  332. # class Restaurant(models.Model):
  333. # place = OneToOneField(Place, primary_key=True):
  334. # Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
  335. # If we didn't have the primary key check, then pk__in (== place__in) would
  336. # give Place's opts as the target opts, but Restaurant isn't compatible
  337. # with that. This logic applies only to primary keys, as when doing __in=qs,
  338. # we are going to turn this into __in=qs.values('pk') later on.
  339. return check(target_opts) or (
  340. getattr(field, "primary_key", False) and check(field.model._meta)
  341. )
  342. class FilteredRelation:
  343. """Specify custom filtering in the ON clause of SQL joins."""
  344. def __init__(self, relation_name, *, condition=Q()):
  345. if not relation_name:
  346. raise ValueError("relation_name cannot be empty.")
  347. self.relation_name = relation_name
  348. self.alias = None
  349. if not isinstance(condition, Q):
  350. raise ValueError("condition argument must be a Q() instance.")
  351. self.condition = condition
  352. self.path = []
  353. def __eq__(self, other):
  354. if not isinstance(other, self.__class__):
  355. return NotImplemented
  356. return (
  357. self.relation_name == other.relation_name
  358. and self.alias == other.alias
  359. and self.condition == other.condition
  360. )
  361. def clone(self):
  362. clone = FilteredRelation(self.relation_name, condition=self.condition)
  363. clone.alias = self.alias
  364. clone.path = self.path[:]
  365. return clone
  366. def resolve_expression(self, *args, **kwargs):
  367. """
  368. QuerySet.annotate() only accepts expression-like arguments
  369. (with a resolve_expression() method).
  370. """
  371. raise NotImplementedError("FilteredRelation.resolve_expression() is unused.")
  372. def as_sql(self, compiler, connection):
  373. # Resolve the condition in Join.filtered_relation.
  374. query = compiler.query
  375. where = query.build_filtered_relation_q(self.condition, reuse=set(self.path))
  376. return compiler.compile(where)