query_utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 contextlib import nullcontext
  12. from django.core.exceptions import FieldError
  13. from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections, models, transaction
  14. from django.db.models.constants import LOOKUP_SEP
  15. from django.utils import tree
  16. from django.utils.functional import cached_property
  17. from django.utils.hashable import make_hashable
  18. logger = logging.getLogger("django.db.models")
  19. PROHIBITED_FILTER_KWARGS = frozenset(["_connector", "_negated"])
  20. # PathInfo is used when converting lookups (fk__somecol). The contents
  21. # describe the relation in Model terms (model Options and Fields for both
  22. # sides of the relation. The join_field is the field backing the relation.
  23. PathInfo = namedtuple(
  24. "PathInfo",
  25. "from_opts to_opts target_fields join_field m2m direct filtered_relation",
  26. )
  27. def subclasses(cls):
  28. yield cls
  29. for subclass in cls.__subclasses__():
  30. yield from subclasses(subclass)
  31. class Q(tree.Node):
  32. """
  33. Encapsulate filters as objects that can then be combined logically (using
  34. `&` and `|`).
  35. """
  36. # Connection types
  37. AND = "AND"
  38. OR = "OR"
  39. XOR = "XOR"
  40. default = AND
  41. conditional = True
  42. connectors = (None, AND, OR, XOR)
  43. def __init__(self, *args, _connector=None, _negated=False, **kwargs):
  44. self._check_connector(_connector)
  45. super().__init__(
  46. children=[*args, *sorted(kwargs.items())],
  47. connector=_connector,
  48. negated=_negated,
  49. )
  50. @classmethod
  51. def create(cls, children=None, connector=None, negated=False):
  52. cls._check_connector(connector)
  53. return super().create(children=children, connector=connector, negated=negated)
  54. @classmethod
  55. def _check_connector(cls, connector):
  56. if connector not in cls.connectors:
  57. connector_reprs = ", ".join(f"{conn!r}" for conn in cls.connectors[1:])
  58. raise ValueError(f"connector must be one of {connector_reprs}, or None.")
  59. def _combine(self, other, conn):
  60. if getattr(other, "conditional", False) is False:
  61. raise TypeError(other)
  62. if not self:
  63. return other.copy()
  64. if not other and isinstance(other, Q):
  65. return self.copy()
  66. obj = self.create(connector=conn)
  67. obj.add(self, conn)
  68. obj.add(other, conn)
  69. return obj
  70. def __or__(self, other):
  71. return self._combine(other, self.OR)
  72. def __and__(self, other):
  73. return self._combine(other, self.AND)
  74. def __xor__(self, other):
  75. return self._combine(other, self.XOR)
  76. def __invert__(self):
  77. obj = self.copy()
  78. obj.negate()
  79. return obj
  80. def resolve_expression(
  81. self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
  82. ):
  83. # We must promote any new joins to left outer joins so that when Q is
  84. # used as an expression, rows aren't filtered due to joins.
  85. clause, joins = query._add_q(
  86. self,
  87. reuse,
  88. allow_joins=allow_joins,
  89. split_subq=False,
  90. check_filterable=False,
  91. summarize=summarize,
  92. )
  93. query.promote_joins(joins)
  94. return clause
  95. def replace_expressions(self, replacements):
  96. if not replacements:
  97. return self
  98. clone = self.create(connector=self.connector, negated=self.negated)
  99. for child in self.children:
  100. child_replacement = child
  101. if isinstance(child, tuple):
  102. lhs, rhs = child
  103. if LOOKUP_SEP in lhs:
  104. path, lookup = lhs.rsplit(LOOKUP_SEP, 1)
  105. else:
  106. path = lhs
  107. lookup = None
  108. field = models.F(path)
  109. if (
  110. field_replacement := field.replace_expressions(replacements)
  111. ) is not field:
  112. # Handle the implicit __exact case by falling back to an
  113. # extra transform when get_lookup returns no match for the
  114. # last component of the path.
  115. if lookup is None:
  116. lookup = "exact"
  117. if (lookup_class := field_replacement.get_lookup(lookup)) is None:
  118. if (
  119. transform_class := field_replacement.get_transform(lookup)
  120. ) is not None:
  121. field_replacement = transform_class(field_replacement)
  122. lookup = "exact"
  123. lookup_class = field_replacement.get_lookup(lookup)
  124. if rhs is None and lookup == "exact":
  125. lookup_class = field_replacement.get_lookup("isnull")
  126. rhs = True
  127. if lookup_class is not None:
  128. child_replacement = lookup_class(field_replacement, rhs)
  129. else:
  130. child_replacement = child.replace_expressions(replacements)
  131. clone.children.append(child_replacement)
  132. return clone
  133. def flatten(self):
  134. """
  135. Recursively yield this Q object and all subexpressions, in depth-first
  136. order.
  137. """
  138. yield self
  139. for child in self.children:
  140. if isinstance(child, tuple):
  141. # Use the lookup.
  142. child = child[1]
  143. if hasattr(child, "flatten"):
  144. yield from child.flatten()
  145. else:
  146. yield child
  147. def check(self, against, using=DEFAULT_DB_ALIAS):
  148. """
  149. Do a database query to check if the expressions of the Q instance
  150. matches against the expressions.
  151. """
  152. # Avoid circular imports.
  153. from django.db.models import Value
  154. from django.db.models.sql import Query
  155. from django.db.models.sql.constants import SINGLE
  156. query = Query(None)
  157. for name, value in against.items():
  158. if not hasattr(value, "resolve_expression"):
  159. value = Value(value)
  160. query.add_annotation(value, name, select=False)
  161. query.add_annotation(Value(1), "_check")
  162. connection = connections[using]
  163. # This will raise a FieldError if a field is missing in "against".
  164. query.add_q(self)
  165. compiler = query.get_compiler(using=using)
  166. context_manager = (
  167. transaction.atomic(using=using)
  168. if connection.in_atomic_block
  169. else nullcontext()
  170. )
  171. try:
  172. with context_manager:
  173. return compiler.execute_sql(SINGLE) is not None
  174. except DatabaseError as e:
  175. logger.warning("Got a database error calling check() on %r: %s", self, e)
  176. return True
  177. def deconstruct(self):
  178. path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
  179. if path.startswith("django.db.models.query_utils"):
  180. path = path.replace("django.db.models.query_utils", "django.db.models")
  181. args = tuple(self.children)
  182. kwargs = {}
  183. if self.connector != self.default:
  184. kwargs["_connector"] = self.connector
  185. if self.negated:
  186. kwargs["_negated"] = True
  187. return path, args, kwargs
  188. @cached_property
  189. def identity(self):
  190. path, args, kwargs = self.deconstruct()
  191. identity = [path, *kwargs.items()]
  192. for child in args:
  193. if isinstance(child, tuple):
  194. arg, value = child
  195. value = make_hashable(value)
  196. identity.append((arg, value))
  197. else:
  198. identity.append(child)
  199. return tuple(identity)
  200. def __eq__(self, other):
  201. if not isinstance(other, Q):
  202. return NotImplemented
  203. return other.identity == self.identity
  204. def __hash__(self):
  205. return hash(self.identity)
  206. @cached_property
  207. def referenced_base_fields(self):
  208. """
  209. Retrieve all base fields referenced directly or through F expressions
  210. excluding any fields referenced through joins.
  211. """
  212. # Avoid circular imports.
  213. from django.db.models.sql import query
  214. return {
  215. child.split(LOOKUP_SEP, 1)[0] for child in query.get_children_from_q(self)
  216. }
  217. class DeferredAttribute:
  218. """
  219. A wrapper for a deferred-loading field. When the value is read from this
  220. object the first time, the query is executed.
  221. """
  222. def __init__(self, field):
  223. self.field = field
  224. def __get__(self, instance, cls=None):
  225. """
  226. Retrieve and caches the value from the datastore on the first lookup.
  227. Return the cached value.
  228. """
  229. if instance is None:
  230. return self
  231. data = instance.__dict__
  232. field_name = self.field.attname
  233. if field_name not in data:
  234. # Let's see if the field is part of the parent chain. If so we
  235. # might be able to reuse the already loaded value. Refs #18343.
  236. val = self._check_parent_chain(instance)
  237. if val is None:
  238. if not instance._is_pk_set():
  239. raise AttributeError(
  240. f"Cannot retrieve deferred field {field_name!r} "
  241. "from an unsaved model."
  242. )
  243. instance._state.fetch_mode.fetch(self, instance)
  244. else:
  245. data[field_name] = val
  246. return data[field_name]
  247. def _check_parent_chain(self, instance):
  248. """
  249. Check if the field value can be fetched from a parent field already
  250. loaded in the instance. This can be done if the to-be fetched
  251. field is a primary key field.
  252. """
  253. opts = instance._meta
  254. link_field = opts.get_ancestor_link(self.field.model)
  255. if self.field.primary_key and self.field != link_field:
  256. return getattr(instance, link_field.attname)
  257. return None
  258. def fetch_one(self, instance):
  259. instance.refresh_from_db(fields=[self.field.attname])
  260. def fetch_many(self, instances):
  261. attname = self.field.attname
  262. db = instances[0]._state.db
  263. value_by_pk = (
  264. self.field.model._base_manager.using(db)
  265. .values_list(attname, flat=True)
  266. .in_bulk({i.pk for i in instances})
  267. )
  268. for instance in instances:
  269. setattr(instance, attname, value_by_pk[instance.pk])
  270. class class_or_instance_method:
  271. """
  272. Hook used in RegisterLookupMixin to return partial functions depending on
  273. the caller type (instance or class of models.Field).
  274. """
  275. def __init__(self, class_method, instance_method):
  276. self.class_method = class_method
  277. self.instance_method = instance_method
  278. def __get__(self, instance, owner):
  279. if instance is None:
  280. return functools.partial(self.class_method, owner)
  281. return functools.partial(self.instance_method, instance)
  282. class RegisterLookupMixin:
  283. def _get_lookup(self, lookup_name):
  284. return self.get_lookups().get(lookup_name, None)
  285. @functools.cache
  286. def get_class_lookups(cls):
  287. class_lookups = [
  288. parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls)
  289. ]
  290. return cls.merge_dicts(class_lookups)
  291. def get_instance_lookups(self):
  292. class_lookups = self.get_class_lookups()
  293. if instance_lookups := getattr(self, "instance_lookups", None):
  294. return {**class_lookups, **instance_lookups}
  295. return class_lookups
  296. get_lookups = class_or_instance_method(get_class_lookups, get_instance_lookups)
  297. get_class_lookups = classmethod(get_class_lookups)
  298. def get_lookup(self, lookup_name):
  299. from django.db.models.lookups import Lookup
  300. found = self._get_lookup(lookup_name)
  301. if found is None and hasattr(self, "output_field"):
  302. return self.output_field.get_lookup(lookup_name)
  303. if found is not None and not issubclass(found, Lookup):
  304. return None
  305. return found
  306. def get_transform(self, lookup_name):
  307. from django.db.models.lookups import Transform
  308. found = self._get_lookup(lookup_name)
  309. if found is None and hasattr(self, "output_field"):
  310. return self.output_field.get_transform(lookup_name)
  311. if found is not None and not issubclass(found, Transform):
  312. return None
  313. return found
  314. @staticmethod
  315. def merge_dicts(dicts):
  316. """
  317. Merge dicts in reverse to preference the order of the original list.
  318. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in
  319. 'b'.
  320. """
  321. merged = {}
  322. for d in reversed(dicts):
  323. merged.update(d)
  324. return merged
  325. @classmethod
  326. def _clear_cached_class_lookups(cls):
  327. for subclass in subclasses(cls):
  328. subclass.get_class_lookups.cache_clear()
  329. def register_class_lookup(cls, lookup, lookup_name=None):
  330. if lookup_name is None:
  331. lookup_name = lookup.lookup_name
  332. if "class_lookups" not in cls.__dict__:
  333. cls.class_lookups = {}
  334. cls.class_lookups[lookup_name] = lookup
  335. cls._clear_cached_class_lookups()
  336. return lookup
  337. def register_instance_lookup(self, lookup, lookup_name=None):
  338. if lookup_name is None:
  339. lookup_name = lookup.lookup_name
  340. if "instance_lookups" not in self.__dict__:
  341. self.instance_lookups = {}
  342. self.instance_lookups[lookup_name] = lookup
  343. return lookup
  344. register_lookup = class_or_instance_method(
  345. register_class_lookup, register_instance_lookup
  346. )
  347. register_class_lookup = classmethod(register_class_lookup)
  348. def _unregister_class_lookup(cls, lookup, lookup_name=None):
  349. """
  350. Remove given lookup from cls lookups. For use in tests only as it's
  351. not thread-safe.
  352. """
  353. if lookup_name is None:
  354. lookup_name = lookup.lookup_name
  355. del cls.class_lookups[lookup_name]
  356. cls._clear_cached_class_lookups()
  357. def _unregister_instance_lookup(self, lookup, lookup_name=None):
  358. """
  359. Remove given lookup from instance lookups. For use in tests only as
  360. it's not thread-safe.
  361. """
  362. if lookup_name is None:
  363. lookup_name = lookup.lookup_name
  364. del self.instance_lookups[lookup_name]
  365. _unregister_lookup = class_or_instance_method(
  366. _unregister_class_lookup, _unregister_instance_lookup
  367. )
  368. _unregister_class_lookup = classmethod(_unregister_class_lookup)
  369. def select_related_descend(field, restricted, requested, select_mask):
  370. """
  371. Return whether `field` should be used to descend deeper for
  372. `select_related()` purposes.
  373. Arguments:
  374. * `field` - the field to be checked. Can be either a `Field` or
  375. `ForeignObjectRel` instance.
  376. * `restricted` - a boolean field, indicating if the field list has been
  377. manually restricted using a select_related() clause.
  378. * `requested` - the select_related() dictionary.
  379. * `select_mask` - the dictionary of selected fields.
  380. """
  381. # Only relationships can be descended.
  382. if not field.remote_field:
  383. return False
  384. # Forward MTI parent links should not be explicitly descended as they are
  385. # always JOIN'ed against (unless excluded by `select_mask`).
  386. if getattr(field.remote_field, "parent_link", False):
  387. return False
  388. # When `select_related()` is used without a `*requested` mask all
  389. # relationships are descended unless they are nullable.
  390. if not restricted:
  391. return not field.null
  392. # When `select_related(*requested)` is used only fields that are part of
  393. # `requested` should be descended.
  394. if field.name not in requested:
  395. return False
  396. # Prevent invalid usages of `select_related()` and `only()`/`defer()` such
  397. # as `select_related("a").only("b")` and `select_related("a").defer("a")`.
  398. if select_mask and field not in select_mask:
  399. raise FieldError(
  400. f"Field {field.model._meta.object_name}.{field.name} cannot be both "
  401. "deferred and traversed using select_related at the same time."
  402. )
  403. return True
  404. def refs_expression(lookup_parts, annotations):
  405. """
  406. Check if the lookup_parts contains references to the given annotations set.
  407. Because the LOOKUP_SEP is contained in the default annotation names, check
  408. each prefix of the lookup_parts for a match.
  409. """
  410. for n in range(1, len(lookup_parts) + 1):
  411. level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
  412. if annotations.get(level_n_lookup):
  413. return level_n_lookup, lookup_parts[n:]
  414. return None, ()
  415. def check_rel_lookup_compatibility(model, target_opts, field):
  416. """
  417. Check that self.model is compatible with target_opts. Compatibility
  418. is OK if:
  419. 1) model and opts match (where proxy inheritance is removed)
  420. 2) model is parent of opts' model or the other way around
  421. """
  422. def check(opts):
  423. return (
  424. model._meta.concrete_model == opts.concrete_model
  425. or opts.concrete_model in model._meta.all_parents
  426. or model in opts.all_parents
  427. )
  428. # If the field is a primary key, then doing a query against the field's
  429. # model is ok, too. Consider the case:
  430. # class Restaurant(models.Model):
  431. # place = OneToOneField(Place, primary_key=True):
  432. # Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
  433. # If we didn't have the primary key check, then pk__in (== place__in) would
  434. # give Place's opts as the target opts, but Restaurant isn't compatible
  435. # with that. This logic applies only to primary keys, as when doing
  436. # __in=qs, we are going to turn this into __in=qs.values('pk') later on.
  437. return check(target_opts) or (
  438. getattr(field, "primary_key", False) and check(field.model._meta)
  439. )
  440. class FilteredRelation:
  441. """Specify custom filtering in the ON clause of SQL joins."""
  442. def __init__(self, relation_name, *, condition=Q()):
  443. if not relation_name:
  444. raise ValueError("relation_name cannot be empty.")
  445. self.relation_name = relation_name
  446. self.alias = None
  447. if not isinstance(condition, Q):
  448. raise ValueError("condition argument must be a Q() instance.")
  449. # .condition and .resolved_condition have to be stored independently
  450. # as the former must remain unchanged for Join.__eq__ to remain stable
  451. # and reusable even once their .filtered_relation are resolved.
  452. self.condition = condition
  453. self.resolved_condition = None
  454. def __eq__(self, other):
  455. if not isinstance(other, self.__class__):
  456. return NotImplemented
  457. return (
  458. self.relation_name == other.relation_name
  459. and self.alias == other.alias
  460. and self.condition == other.condition
  461. )
  462. def clone(self):
  463. clone = FilteredRelation(self.relation_name, condition=self.condition)
  464. clone.alias = self.alias
  465. if (resolved_condition := self.resolved_condition) is not None:
  466. clone.resolved_condition = resolved_condition.clone()
  467. return clone
  468. def relabeled_clone(self, change_map):
  469. clone = self.clone()
  470. if resolved_condition := clone.resolved_condition:
  471. clone.resolved_condition = resolved_condition.relabeled_clone(change_map)
  472. return clone
  473. def resolve_expression(self, query, reuse, *args, **kwargs):
  474. clone = self.clone()
  475. clone.resolved_condition = query.build_filter(
  476. self.condition,
  477. can_reuse=reuse,
  478. allow_joins=True,
  479. split_subq=False,
  480. update_join_types=False,
  481. )[0]
  482. return clone
  483. def as_sql(self, compiler, connection):
  484. return compiler.compile(self.resolved_condition)