query.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. """
  2. Create SQL statements for QuerySets.
  3. The code in here encapsulates all of the SQL construction so that QuerySets
  4. themselves do not have to (and could be backed by things other than SQL
  5. databases). The abstraction barrier only works one way: this module has to know
  6. all about the internals of models in order to get the information it needs.
  7. """
  8. import copy
  9. import difflib
  10. import functools
  11. import inspect
  12. import sys
  13. import warnings
  14. from collections import Counter, namedtuple
  15. from collections.abc import Iterator, Mapping
  16. from itertools import chain, count, product
  17. from string import ascii_uppercase
  18. from django.core.exceptions import (
  19. EmptyResultSet, FieldDoesNotExist, FieldError,
  20. )
  21. from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections
  22. from django.db.models.aggregates import Count
  23. from django.db.models.constants import LOOKUP_SEP
  24. from django.db.models.expressions import (
  25. BaseExpression, Col, F, OuterRef, Ref, SimpleCol,
  26. )
  27. from django.db.models.fields import Field
  28. from django.db.models.fields.related_lookups import MultiColSource
  29. from django.db.models.lookups import Lookup
  30. from django.db.models.query_utils import (
  31. Q, check_rel_lookup_compatibility, refs_expression,
  32. )
  33. from django.db.models.sql.constants import (
  34. INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE,
  35. )
  36. from django.db.models.sql.datastructures import (
  37. BaseTable, Empty, Join, MultiJoin,
  38. )
  39. from django.db.models.sql.where import (
  40. AND, OR, ExtraWhere, NothingNode, WhereNode,
  41. )
  42. from django.utils.deprecation import RemovedInDjango40Warning
  43. from django.utils.functional import cached_property
  44. from django.utils.tree import Node
  45. __all__ = ['Query', 'RawQuery']
  46. def get_field_names_from_opts(opts):
  47. return set(chain.from_iterable(
  48. (f.name, f.attname) if f.concrete else (f.name,)
  49. for f in opts.get_fields()
  50. ))
  51. def get_children_from_q(q):
  52. for child in q.children:
  53. if isinstance(child, Node):
  54. yield from get_children_from_q(child)
  55. else:
  56. yield child
  57. JoinInfo = namedtuple(
  58. 'JoinInfo',
  59. ('final_field', 'targets', 'opts', 'joins', 'path', 'transform_function')
  60. )
  61. def _get_col(target, field, alias, simple_col):
  62. if simple_col:
  63. return SimpleCol(target, field)
  64. return target.get_col(alias, field)
  65. class RawQuery:
  66. """A single raw SQL query."""
  67. def __init__(self, sql, using, params=None):
  68. self.params = params or ()
  69. self.sql = sql
  70. self.using = using
  71. self.cursor = None
  72. # Mirror some properties of a normal query so that
  73. # the compiler can be used to process results.
  74. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  75. self.extra_select = {}
  76. self.annotation_select = {}
  77. def chain(self, using):
  78. return self.clone(using)
  79. def clone(self, using):
  80. return RawQuery(self.sql, using, params=self.params)
  81. def get_columns(self):
  82. if self.cursor is None:
  83. self._execute_query()
  84. converter = connections[self.using].introspection.identifier_converter
  85. return [converter(column_meta[0])
  86. for column_meta in self.cursor.description]
  87. def __iter__(self):
  88. # Always execute a new query for a new iterator.
  89. # This could be optimized with a cache at the expense of RAM.
  90. self._execute_query()
  91. if not connections[self.using].features.can_use_chunked_reads:
  92. # If the database can't use chunked reads we need to make sure we
  93. # evaluate the entire query up front.
  94. result = list(self.cursor)
  95. else:
  96. result = self.cursor
  97. return iter(result)
  98. def __repr__(self):
  99. return "<%s: %s>" % (self.__class__.__name__, self)
  100. @property
  101. def params_type(self):
  102. return dict if isinstance(self.params, Mapping) else tuple
  103. def __str__(self):
  104. return self.sql % self.params_type(self.params)
  105. def _execute_query(self):
  106. connection = connections[self.using]
  107. # Adapt parameters to the database, as much as possible considering
  108. # that the target type isn't known. See #17755.
  109. params_type = self.params_type
  110. adapter = connection.ops.adapt_unknown_value
  111. if params_type is tuple:
  112. params = tuple(adapter(val) for val in self.params)
  113. elif params_type is dict:
  114. params = {key: adapter(val) for key, val in self.params.items()}
  115. else:
  116. raise RuntimeError("Unexpected params type: %s" % params_type)
  117. self.cursor = connection.cursor()
  118. self.cursor.execute(self.sql, params)
  119. class Query(BaseExpression):
  120. """A single SQL query."""
  121. alias_prefix = 'T'
  122. subq_aliases = frozenset([alias_prefix])
  123. compiler = 'SQLCompiler'
  124. def __init__(self, model, where=WhereNode):
  125. self.model = model
  126. self.alias_refcount = {}
  127. # alias_map is the most important data structure regarding joins.
  128. # It's used for recording which joins exist in the query and what
  129. # types they are. The key is the alias of the joined table (possibly
  130. # the table name) and the value is a Join-like object (see
  131. # sql.datastructures.Join for more information).
  132. self.alias_map = {}
  133. # Sometimes the query contains references to aliases in outer queries (as
  134. # a result of split_exclude). Correct alias quoting needs to know these
  135. # aliases too.
  136. # Map external tables to whether they are aliased.
  137. self.external_aliases = {}
  138. self.table_map = {} # Maps table names to list of aliases.
  139. self.default_cols = True
  140. self.default_ordering = True
  141. self.standard_ordering = True
  142. self.used_aliases = set()
  143. self.filter_is_sticky = False
  144. self.subquery = False
  145. # SQL-related attributes
  146. # Select and related select clauses are expressions to use in the
  147. # SELECT clause of the query.
  148. # The select is used for cases where we want to set up the select
  149. # clause to contain other than default fields (values(), subqueries...)
  150. # Note that annotations go to annotations dictionary.
  151. self.select = ()
  152. self.where = where()
  153. self.where_class = where
  154. # The group_by attribute can have one of the following forms:
  155. # - None: no group by at all in the query
  156. # - A tuple of expressions: group by (at least) those expressions.
  157. # String refs are also allowed for now.
  158. # - True: group by all select fields of the model
  159. # See compiler.get_group_by() for details.
  160. self.group_by = None
  161. self.order_by = ()
  162. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  163. self.distinct = False
  164. self.distinct_fields = ()
  165. self.select_for_update = False
  166. self.select_for_update_nowait = False
  167. self.select_for_update_skip_locked = False
  168. self.select_for_update_of = ()
  169. self.select_related = False
  170. # Arbitrary limit for select_related to prevents infinite recursion.
  171. self.max_depth = 5
  172. # Holds the selects defined by a call to values() or values_list()
  173. # excluding annotation_select and extra_select.
  174. self.values_select = ()
  175. # SQL annotation-related attributes
  176. self.annotations = {} # Maps alias -> Annotation Expression
  177. self.annotation_select_mask = None
  178. self._annotation_select_cache = None
  179. # Set combination attributes
  180. self.combinator = None
  181. self.combinator_all = False
  182. self.combined_queries = ()
  183. # These are for extensions. The contents are more or less appended
  184. # verbatim to the appropriate clause.
  185. self.extra = {} # Maps col_alias -> (col_sql, params).
  186. self.extra_select_mask = None
  187. self._extra_select_cache = None
  188. self.extra_tables = ()
  189. self.extra_order_by = ()
  190. # A tuple that is a set of model field names and either True, if these
  191. # are the fields to defer, or False if these are the only fields to
  192. # load.
  193. self.deferred_loading = (frozenset(), True)
  194. self._filtered_relations = {}
  195. self.explain_query = False
  196. self.explain_format = None
  197. self.explain_options = {}
  198. @property
  199. def output_field(self):
  200. if len(self.select) == 1:
  201. return self.select[0].field
  202. elif len(self.annotation_select) == 1:
  203. return next(iter(self.annotation_select.values())).output_field
  204. @property
  205. def has_select_fields(self):
  206. return bool(self.select or self.annotation_select_mask or self.extra_select_mask)
  207. @cached_property
  208. def base_table(self):
  209. for alias in self.alias_map:
  210. return alias
  211. def __str__(self):
  212. """
  213. Return the query as a string of SQL with the parameter values
  214. substituted in (use sql_with_params() to see the unsubstituted string).
  215. Parameter values won't necessarily be quoted correctly, since that is
  216. done by the database interface at execution time.
  217. """
  218. sql, params = self.sql_with_params()
  219. return sql % params
  220. def sql_with_params(self):
  221. """
  222. Return the query as an SQL string and the parameters that will be
  223. substituted into the query.
  224. """
  225. return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
  226. def __deepcopy__(self, memo):
  227. """Limit the amount of work when a Query is deepcopied."""
  228. result = self.clone()
  229. memo[id(self)] = result
  230. return result
  231. def get_compiler(self, using=None, connection=None):
  232. if using is None and connection is None:
  233. raise ValueError("Need either using or connection")
  234. if using:
  235. connection = connections[using]
  236. return connection.ops.compiler(self.compiler)(self, connection, using)
  237. def get_meta(self):
  238. """
  239. Return the Options instance (the model._meta) from which to start
  240. processing. Normally, this is self.model._meta, but it can be changed
  241. by subclasses.
  242. """
  243. return self.model._meta
  244. def clone(self):
  245. """
  246. Return a copy of the current Query. A lightweight alternative to
  247. to deepcopy().
  248. """
  249. obj = Empty()
  250. obj.__class__ = self.__class__
  251. # Copy references to everything.
  252. obj.__dict__ = self.__dict__.copy()
  253. # Clone attributes that can't use shallow copy.
  254. obj.alias_refcount = self.alias_refcount.copy()
  255. obj.alias_map = self.alias_map.copy()
  256. obj.external_aliases = self.external_aliases.copy()
  257. obj.table_map = self.table_map.copy()
  258. obj.where = self.where.clone()
  259. obj.annotations = self.annotations.copy()
  260. if self.annotation_select_mask is None:
  261. obj.annotation_select_mask = None
  262. else:
  263. obj.annotation_select_mask = self.annotation_select_mask.copy()
  264. # _annotation_select_cache cannot be copied, as doing so breaks the
  265. # (necessary) state in which both annotations and
  266. # _annotation_select_cache point to the same underlying objects.
  267. # It will get re-populated in the cloned queryset the next time it's
  268. # used.
  269. obj._annotation_select_cache = None
  270. obj.extra = self.extra.copy()
  271. if self.extra_select_mask is None:
  272. obj.extra_select_mask = None
  273. else:
  274. obj.extra_select_mask = self.extra_select_mask.copy()
  275. if self._extra_select_cache is None:
  276. obj._extra_select_cache = None
  277. else:
  278. obj._extra_select_cache = self._extra_select_cache.copy()
  279. if self.select_related is not False:
  280. # Use deepcopy because select_related stores fields in nested
  281. # dicts.
  282. obj.select_related = copy.deepcopy(obj.select_related)
  283. if 'subq_aliases' in self.__dict__:
  284. obj.subq_aliases = self.subq_aliases.copy()
  285. obj.used_aliases = self.used_aliases.copy()
  286. obj._filtered_relations = self._filtered_relations.copy()
  287. # Clear the cached_property
  288. try:
  289. del obj.base_table
  290. except AttributeError:
  291. pass
  292. return obj
  293. def chain(self, klass=None):
  294. """
  295. Return a copy of the current Query that's ready for another operation.
  296. The klass argument changes the type of the Query, e.g. UpdateQuery.
  297. """
  298. obj = self.clone()
  299. if klass and obj.__class__ != klass:
  300. obj.__class__ = klass
  301. if not obj.filter_is_sticky:
  302. obj.used_aliases = set()
  303. obj.filter_is_sticky = False
  304. if hasattr(obj, '_setup_query'):
  305. obj._setup_query()
  306. return obj
  307. def relabeled_clone(self, change_map):
  308. clone = self.clone()
  309. clone.change_aliases(change_map)
  310. return clone
  311. def rewrite_cols(self, annotation, col_cnt):
  312. # We must make sure the inner query has the referred columns in it.
  313. # If we are aggregating over an annotation, then Django uses Ref()
  314. # instances to note this. However, if we are annotating over a column
  315. # of a related model, then it might be that column isn't part of the
  316. # SELECT clause of the inner query, and we must manually make sure
  317. # the column is selected. An example case is:
  318. # .aggregate(Sum('author__awards'))
  319. # Resolving this expression results in a join to author, but there
  320. # is no guarantee the awards column of author is in the select clause
  321. # of the query. Thus we must manually add the column to the inner
  322. # query.
  323. orig_exprs = annotation.get_source_expressions()
  324. new_exprs = []
  325. for expr in orig_exprs:
  326. # FIXME: These conditions are fairly arbitrary. Identify a better
  327. # method of having expressions decide which code path they should
  328. # take.
  329. if isinstance(expr, Ref):
  330. # Its already a Ref to subquery (see resolve_ref() for
  331. # details)
  332. new_exprs.append(expr)
  333. elif isinstance(expr, (WhereNode, Lookup)):
  334. # Decompose the subexpressions further. The code here is
  335. # copied from the else clause, but this condition must appear
  336. # before the contains_aggregate/is_summary condition below.
  337. new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
  338. new_exprs.append(new_expr)
  339. else:
  340. # Reuse aliases of expressions already selected in subquery.
  341. for col_alias, selected_annotation in self.annotation_select.items():
  342. if selected_annotation == expr:
  343. new_expr = Ref(col_alias, expr)
  344. break
  345. else:
  346. # An expression that is not selected the subquery.
  347. if isinstance(expr, Col) or (expr.contains_aggregate and not expr.is_summary):
  348. # Reference column or another aggregate. Select it
  349. # under a non-conflicting alias.
  350. col_cnt += 1
  351. col_alias = '__col%d' % col_cnt
  352. self.annotations[col_alias] = expr
  353. self.append_annotation_mask([col_alias])
  354. new_expr = Ref(col_alias, expr)
  355. else:
  356. # Some other expression not referencing database values
  357. # directly. Its subexpression might contain Cols.
  358. new_expr, col_cnt = self.rewrite_cols(expr, col_cnt)
  359. new_exprs.append(new_expr)
  360. annotation.set_source_expressions(new_exprs)
  361. return annotation, col_cnt
  362. def get_aggregation(self, using, added_aggregate_names):
  363. """
  364. Return the dictionary with the values of the existing aggregations.
  365. """
  366. if not self.annotation_select:
  367. return {}
  368. existing_annotations = [
  369. annotation for alias, annotation
  370. in self.annotations.items()
  371. if alias not in added_aggregate_names
  372. ]
  373. # Decide if we need to use a subquery.
  374. #
  375. # Existing annotations would cause incorrect results as get_aggregation()
  376. # must produce just one result and thus must not use GROUP BY. But we
  377. # aren't smart enough to remove the existing annotations from the
  378. # query, so those would force us to use GROUP BY.
  379. #
  380. # If the query has limit or distinct, or uses set operations, then
  381. # those operations must be done in a subquery so that the query
  382. # aggregates on the limit and/or distinct results instead of applying
  383. # the distinct and limit after the aggregation.
  384. if (isinstance(self.group_by, tuple) or self.is_sliced or existing_annotations or
  385. self.distinct or self.combinator):
  386. from django.db.models.sql.subqueries import AggregateQuery
  387. outer_query = AggregateQuery(self.model)
  388. inner_query = self.clone()
  389. inner_query.select_for_update = False
  390. inner_query.select_related = False
  391. inner_query.set_annotation_mask(self.annotation_select)
  392. if not self.is_sliced and not self.distinct_fields:
  393. # Queries with distinct_fields need ordering and when a limit
  394. # is applied we must take the slice from the ordered query.
  395. # Otherwise no need for ordering.
  396. inner_query.clear_ordering(True)
  397. if not inner_query.distinct:
  398. # If the inner query uses default select and it has some
  399. # aggregate annotations, then we must make sure the inner
  400. # query is grouped by the main model's primary key. However,
  401. # clearing the select clause can alter results if distinct is
  402. # used.
  403. has_existing_aggregate_annotations = any(
  404. annotation for annotation in existing_annotations
  405. if getattr(annotation, 'contains_aggregate', True)
  406. )
  407. if inner_query.default_cols and has_existing_aggregate_annotations:
  408. inner_query.group_by = (self.model._meta.pk.get_col(inner_query.get_initial_alias()),)
  409. inner_query.default_cols = False
  410. relabels = {t: 'subquery' for t in inner_query.alias_map}
  411. relabels[None] = 'subquery'
  412. # Remove any aggregates marked for reduction from the subquery
  413. # and move them to the outer AggregateQuery.
  414. col_cnt = 0
  415. for alias, expression in list(inner_query.annotation_select.items()):
  416. annotation_select_mask = inner_query.annotation_select_mask
  417. if expression.is_summary:
  418. expression, col_cnt = inner_query.rewrite_cols(expression, col_cnt)
  419. outer_query.annotations[alias] = expression.relabeled_clone(relabels)
  420. del inner_query.annotations[alias]
  421. annotation_select_mask.remove(alias)
  422. # Make sure the annotation_select wont use cached results.
  423. inner_query.set_annotation_mask(inner_query.annotation_select_mask)
  424. if inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask:
  425. # In case of Model.objects[0:3].count(), there would be no
  426. # field selected in the inner query, yet we must use a subquery.
  427. # So, make sure at least one field is selected.
  428. inner_query.select = (self.model._meta.pk.get_col(inner_query.get_initial_alias()),)
  429. try:
  430. outer_query.add_subquery(inner_query, using)
  431. except EmptyResultSet:
  432. return {
  433. alias: None
  434. for alias in outer_query.annotation_select
  435. }
  436. else:
  437. outer_query = self
  438. self.select = ()
  439. self.default_cols = False
  440. self.extra = {}
  441. outer_query.clear_ordering(True)
  442. outer_query.clear_limits()
  443. outer_query.select_for_update = False
  444. outer_query.select_related = False
  445. compiler = outer_query.get_compiler(using)
  446. result = compiler.execute_sql(SINGLE)
  447. if result is None:
  448. result = [None] * len(outer_query.annotation_select)
  449. converters = compiler.get_converters(outer_query.annotation_select.values())
  450. result = next(compiler.apply_converters((result,), converters))
  451. return dict(zip(outer_query.annotation_select, result))
  452. def get_count(self, using):
  453. """
  454. Perform a COUNT() query using the current filter constraints.
  455. """
  456. obj = self.clone()
  457. obj.add_annotation(Count('*'), alias='__count', is_summary=True)
  458. number = obj.get_aggregation(using, ['__count'])['__count']
  459. if number is None:
  460. number = 0
  461. return number
  462. def has_filters(self):
  463. return self.where
  464. def has_results(self, using):
  465. q = self.clone()
  466. if not q.distinct:
  467. if q.group_by is True:
  468. q.add_fields((f.attname for f in self.model._meta.concrete_fields), False)
  469. # Disable GROUP BY aliases to avoid orphaning references to the
  470. # SELECT clause which is about to be cleared.
  471. q.set_group_by(allow_aliases=False)
  472. q.clear_select_clause()
  473. q.clear_ordering(True)
  474. q.set_limits(high=1)
  475. compiler = q.get_compiler(using=using)
  476. return compiler.has_results()
  477. def explain(self, using, format=None, **options):
  478. q = self.clone()
  479. q.explain_query = True
  480. q.explain_format = format
  481. q.explain_options = options
  482. compiler = q.get_compiler(using=using)
  483. return '\n'.join(compiler.explain_query())
  484. def combine(self, rhs, connector):
  485. """
  486. Merge the 'rhs' query into the current one (with any 'rhs' effects
  487. being applied *after* (that is, "to the right of") anything in the
  488. current query. 'rhs' is not modified during a call to this function.
  489. The 'connector' parameter describes how to connect filters from the
  490. 'rhs' query.
  491. """
  492. assert self.model == rhs.model, \
  493. "Cannot combine queries on two different base models."
  494. assert not self.is_sliced, \
  495. "Cannot combine queries once a slice has been taken."
  496. assert self.distinct == rhs.distinct, \
  497. "Cannot combine a unique query with a non-unique query."
  498. assert self.distinct_fields == rhs.distinct_fields, \
  499. "Cannot combine queries with different distinct fields."
  500. # Work out how to relabel the rhs aliases, if necessary.
  501. change_map = {}
  502. conjunction = (connector == AND)
  503. # Determine which existing joins can be reused. When combining the
  504. # query with AND we must recreate all joins for m2m filters. When
  505. # combining with OR we can reuse joins. The reason is that in AND
  506. # case a single row can't fulfill a condition like:
  507. # revrel__col=1 & revrel__col=2
  508. # But, there might be two different related rows matching this
  509. # condition. In OR case a single True is enough, so single row is
  510. # enough, too.
  511. #
  512. # Note that we will be creating duplicate joins for non-m2m joins in
  513. # the AND case. The results will be correct but this creates too many
  514. # joins. This is something that could be fixed later on.
  515. reuse = set() if conjunction else set(self.alias_map)
  516. # Base table must be present in the query - this is the same
  517. # table on both sides.
  518. self.get_initial_alias()
  519. joinpromoter = JoinPromoter(connector, 2, False)
  520. joinpromoter.add_votes(
  521. j for j in self.alias_map if self.alias_map[j].join_type == INNER)
  522. rhs_votes = set()
  523. # Now, add the joins from rhs query into the new query (skipping base
  524. # table).
  525. rhs_tables = list(rhs.alias_map)[1:]
  526. for alias in rhs_tables:
  527. join = rhs.alias_map[alias]
  528. # If the left side of the join was already relabeled, use the
  529. # updated alias.
  530. join = join.relabeled_clone(change_map)
  531. new_alias = self.join(join, reuse=reuse)
  532. if join.join_type == INNER:
  533. rhs_votes.add(new_alias)
  534. # We can't reuse the same join again in the query. If we have two
  535. # distinct joins for the same connection in rhs query, then the
  536. # combined query must have two joins, too.
  537. reuse.discard(new_alias)
  538. if alias != new_alias:
  539. change_map[alias] = new_alias
  540. if not rhs.alias_refcount[alias]:
  541. # The alias was unused in the rhs query. Unref it so that it
  542. # will be unused in the new query, too. We have to add and
  543. # unref the alias so that join promotion has information of
  544. # the join type for the unused alias.
  545. self.unref_alias(new_alias)
  546. joinpromoter.add_votes(rhs_votes)
  547. joinpromoter.update_join_types(self)
  548. # Now relabel a copy of the rhs where-clause and add it to the current
  549. # one.
  550. w = rhs.where.clone()
  551. w.relabel_aliases(change_map)
  552. self.where.add(w, connector)
  553. # Selection columns and extra extensions are those provided by 'rhs'.
  554. if rhs.select:
  555. self.set_select([col.relabeled_clone(change_map) for col in rhs.select])
  556. else:
  557. self.select = ()
  558. if connector == OR:
  559. # It would be nice to be able to handle this, but the queries don't
  560. # really make sense (or return consistent value sets). Not worth
  561. # the extra complexity when you can write a real query instead.
  562. if self.extra and rhs.extra:
  563. raise ValueError("When merging querysets using 'or', you cannot have extra(select=...) on both sides.")
  564. self.extra.update(rhs.extra)
  565. extra_select_mask = set()
  566. if self.extra_select_mask is not None:
  567. extra_select_mask.update(self.extra_select_mask)
  568. if rhs.extra_select_mask is not None:
  569. extra_select_mask.update(rhs.extra_select_mask)
  570. if extra_select_mask:
  571. self.set_extra_mask(extra_select_mask)
  572. self.extra_tables += rhs.extra_tables
  573. # Ordering uses the 'rhs' ordering, unless it has none, in which case
  574. # the current ordering is used.
  575. self.order_by = rhs.order_by or self.order_by
  576. self.extra_order_by = rhs.extra_order_by or self.extra_order_by
  577. def deferred_to_data(self, target, callback):
  578. """
  579. Convert the self.deferred_loading data structure to an alternate data
  580. structure, describing the field that *will* be loaded. This is used to
  581. compute the columns to select from the database and also by the
  582. QuerySet class to work out which fields are being initialized on each
  583. model. Models that have all their fields included aren't mentioned in
  584. the result, only those that have field restrictions in place.
  585. The "target" parameter is the instance that is populated (in place).
  586. The "callback" is a function that is called whenever a (model, field)
  587. pair need to be added to "target". It accepts three parameters:
  588. "target", and the model and list of fields being added for that model.
  589. """
  590. field_names, defer = self.deferred_loading
  591. if not field_names:
  592. return
  593. orig_opts = self.get_meta()
  594. seen = {}
  595. must_include = {orig_opts.concrete_model: {orig_opts.pk}}
  596. for field_name in field_names:
  597. parts = field_name.split(LOOKUP_SEP)
  598. cur_model = self.model._meta.concrete_model
  599. opts = orig_opts
  600. for name in parts[:-1]:
  601. old_model = cur_model
  602. if name in self._filtered_relations:
  603. name = self._filtered_relations[name].relation_name
  604. source = opts.get_field(name)
  605. if is_reverse_o2o(source):
  606. cur_model = source.related_model
  607. else:
  608. cur_model = source.remote_field.model
  609. opts = cur_model._meta
  610. # Even if we're "just passing through" this model, we must add
  611. # both the current model's pk and the related reference field
  612. # (if it's not a reverse relation) to the things we select.
  613. if not is_reverse_o2o(source):
  614. must_include[old_model].add(source)
  615. add_to_dict(must_include, cur_model, opts.pk)
  616. field = opts.get_field(parts[-1])
  617. is_reverse_object = field.auto_created and not field.concrete
  618. model = field.related_model if is_reverse_object else field.model
  619. model = model._meta.concrete_model
  620. if model == opts.model:
  621. model = cur_model
  622. if not is_reverse_o2o(field):
  623. add_to_dict(seen, model, field)
  624. if defer:
  625. # We need to load all fields for each model, except those that
  626. # appear in "seen" (for all models that appear in "seen"). The only
  627. # slight complexity here is handling fields that exist on parent
  628. # models.
  629. workset = {}
  630. for model, values in seen.items():
  631. for field in model._meta.local_fields:
  632. if field not in values:
  633. m = field.model._meta.concrete_model
  634. add_to_dict(workset, m, field)
  635. for model, values in must_include.items():
  636. # If we haven't included a model in workset, we don't add the
  637. # corresponding must_include fields for that model, since an
  638. # empty set means "include all fields". That's why there's no
  639. # "else" branch here.
  640. if model in workset:
  641. workset[model].update(values)
  642. for model, values in workset.items():
  643. callback(target, model, values)
  644. else:
  645. for model, values in must_include.items():
  646. if model in seen:
  647. seen[model].update(values)
  648. else:
  649. # As we've passed through this model, but not explicitly
  650. # included any fields, we have to make sure it's mentioned
  651. # so that only the "must include" fields are pulled in.
  652. seen[model] = values
  653. # Now ensure that every model in the inheritance chain is mentioned
  654. # in the parent list. Again, it must be mentioned to ensure that
  655. # only "must include" fields are pulled in.
  656. for model in orig_opts.get_parent_list():
  657. seen.setdefault(model, set())
  658. for model, values in seen.items():
  659. callback(target, model, values)
  660. def table_alias(self, table_name, create=False, filtered_relation=None):
  661. """
  662. Return a table alias for the given table_name and whether this is a
  663. new alias or not.
  664. If 'create' is true, a new alias is always created. Otherwise, the
  665. most recently created alias for the table (if one exists) is reused.
  666. """
  667. alias_list = self.table_map.get(table_name)
  668. if not create and alias_list:
  669. alias = alias_list[0]
  670. self.alias_refcount[alias] += 1
  671. return alias, False
  672. # Create a new alias for this table.
  673. if alias_list:
  674. alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)
  675. alias_list.append(alias)
  676. else:
  677. # The first occurrence of a table uses the table name directly.
  678. alias = filtered_relation.alias if filtered_relation is not None else table_name
  679. self.table_map[table_name] = [alias]
  680. self.alias_refcount[alias] = 1
  681. return alias, True
  682. def ref_alias(self, alias):
  683. """Increases the reference count for this alias."""
  684. self.alias_refcount[alias] += 1
  685. def unref_alias(self, alias, amount=1):
  686. """Decreases the reference count for this alias."""
  687. self.alias_refcount[alias] -= amount
  688. def promote_joins(self, aliases):
  689. """
  690. Promote recursively the join type of given aliases and its children to
  691. an outer join. If 'unconditional' is False, only promote the join if
  692. it is nullable or the parent join is an outer join.
  693. The children promotion is done to avoid join chains that contain a LOUTER
  694. b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
  695. then we must also promote b->c automatically, or otherwise the promotion
  696. of a->b doesn't actually change anything in the query results.
  697. """
  698. aliases = list(aliases)
  699. while aliases:
  700. alias = aliases.pop(0)
  701. if self.alias_map[alias].join_type is None:
  702. # This is the base table (first FROM entry) - this table
  703. # isn't really joined at all in the query, so we should not
  704. # alter its join type.
  705. continue
  706. # Only the first alias (skipped above) should have None join_type
  707. assert self.alias_map[alias].join_type is not None
  708. parent_alias = self.alias_map[alias].parent_alias
  709. parent_louter = parent_alias and self.alias_map[parent_alias].join_type == LOUTER
  710. already_louter = self.alias_map[alias].join_type == LOUTER
  711. if ((self.alias_map[alias].nullable or parent_louter) and
  712. not already_louter):
  713. self.alias_map[alias] = self.alias_map[alias].promote()
  714. # Join type of 'alias' changed, so re-examine all aliases that
  715. # refer to this one.
  716. aliases.extend(
  717. join for join in self.alias_map
  718. if self.alias_map[join].parent_alias == alias and join not in aliases
  719. )
  720. def demote_joins(self, aliases):
  721. """
  722. Change join type from LOUTER to INNER for all joins in aliases.
  723. Similarly to promote_joins(), this method must ensure no join chains
  724. containing first an outer, then an inner join are generated. If we
  725. are demoting b->c join in chain a LOUTER b LOUTER c then we must
  726. demote a->b automatically, or otherwise the demotion of b->c doesn't
  727. actually change anything in the query results. .
  728. """
  729. aliases = list(aliases)
  730. while aliases:
  731. alias = aliases.pop(0)
  732. if self.alias_map[alias].join_type == LOUTER:
  733. self.alias_map[alias] = self.alias_map[alias].demote()
  734. parent_alias = self.alias_map[alias].parent_alias
  735. if self.alias_map[parent_alias].join_type == INNER:
  736. aliases.append(parent_alias)
  737. def reset_refcounts(self, to_counts):
  738. """
  739. Reset reference counts for aliases so that they match the value passed
  740. in `to_counts`.
  741. """
  742. for alias, cur_refcount in self.alias_refcount.copy().items():
  743. unref_amount = cur_refcount - to_counts.get(alias, 0)
  744. self.unref_alias(alias, unref_amount)
  745. def change_aliases(self, change_map):
  746. """
  747. Change the aliases in change_map (which maps old-alias -> new-alias),
  748. relabelling any references to them in select columns and the where
  749. clause.
  750. """
  751. assert set(change_map).isdisjoint(change_map.values())
  752. # 1. Update references in "select" (normal columns plus aliases),
  753. # "group by" and "where".
  754. self.where.relabel_aliases(change_map)
  755. if isinstance(self.group_by, tuple):
  756. self.group_by = tuple([col.relabeled_clone(change_map) for col in self.group_by])
  757. self.select = tuple([col.relabeled_clone(change_map) for col in self.select])
  758. self.annotations = self.annotations and {
  759. key: col.relabeled_clone(change_map) for key, col in self.annotations.items()
  760. }
  761. # 2. Rename the alias in the internal table/alias datastructures.
  762. for old_alias, new_alias in change_map.items():
  763. if old_alias not in self.alias_map:
  764. continue
  765. alias_data = self.alias_map[old_alias].relabeled_clone(change_map)
  766. self.alias_map[new_alias] = alias_data
  767. self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
  768. del self.alias_refcount[old_alias]
  769. del self.alias_map[old_alias]
  770. table_aliases = self.table_map[alias_data.table_name]
  771. for pos, alias in enumerate(table_aliases):
  772. if alias == old_alias:
  773. table_aliases[pos] = new_alias
  774. break
  775. self.external_aliases = {
  776. # Table is aliased or it's being changed and thus is aliased.
  777. change_map.get(alias, alias): (aliased or alias in change_map)
  778. for alias, aliased in self.external_aliases.items()
  779. }
  780. def bump_prefix(self, outer_query):
  781. """
  782. Change the alias prefix to the next letter in the alphabet in a way
  783. that the outer query's aliases and this query's aliases will not
  784. conflict. Even tables that previously had no alias will get an alias
  785. after this call.
  786. """
  787. def prefix_gen():
  788. """
  789. Generate a sequence of characters in alphabetical order:
  790. -> 'A', 'B', 'C', ...
  791. When the alphabet is finished, the sequence will continue with the
  792. Cartesian product:
  793. -> 'AA', 'AB', 'AC', ...
  794. """
  795. alphabet = ascii_uppercase
  796. prefix = chr(ord(self.alias_prefix) + 1)
  797. yield prefix
  798. for n in count(1):
  799. seq = alphabet[alphabet.index(prefix):] if prefix else alphabet
  800. for s in product(seq, repeat=n):
  801. yield ''.join(s)
  802. prefix = None
  803. if self.alias_prefix != outer_query.alias_prefix:
  804. # No clashes between self and outer query should be possible.
  805. return
  806. # Explicitly avoid infinite loop. The constant divider is based on how
  807. # much depth recursive subquery references add to the stack. This value
  808. # might need to be adjusted when adding or removing function calls from
  809. # the code path in charge of performing these operations.
  810. local_recursion_limit = sys.getrecursionlimit() // 16
  811. for pos, prefix in enumerate(prefix_gen()):
  812. if prefix not in self.subq_aliases:
  813. self.alias_prefix = prefix
  814. break
  815. if pos > local_recursion_limit:
  816. raise RecursionError(
  817. 'Maximum recursion depth exceeded: too many subqueries.'
  818. )
  819. self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
  820. outer_query.subq_aliases = outer_query.subq_aliases.union(self.subq_aliases)
  821. self.change_aliases({
  822. alias: '%s%d' % (self.alias_prefix, pos)
  823. for pos, alias in enumerate(self.alias_map)
  824. })
  825. def get_initial_alias(self):
  826. """
  827. Return the first alias for this query, after increasing its reference
  828. count.
  829. """
  830. if self.alias_map:
  831. alias = self.base_table
  832. self.ref_alias(alias)
  833. else:
  834. alias = self.join(BaseTable(self.get_meta().db_table, None))
  835. return alias
  836. def count_active_tables(self):
  837. """
  838. Return the number of tables in this query with a non-zero reference
  839. count. After execution, the reference counts are zeroed, so tables
  840. added in compiler will not be seen by this method.
  841. """
  842. return len([1 for count in self.alias_refcount.values() if count])
  843. def join(self, join, reuse=None, reuse_with_filtered_relation=False):
  844. """
  845. Return an alias for the 'join', either reusing an existing alias for
  846. that join or creating a new one. 'join' is either a
  847. sql.datastructures.BaseTable or Join.
  848. The 'reuse' parameter can be either None which means all joins are
  849. reusable, or it can be a set containing the aliases that can be reused.
  850. The 'reuse_with_filtered_relation' parameter is used when computing
  851. FilteredRelation instances.
  852. A join is always created as LOUTER if the lhs alias is LOUTER to make
  853. sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new
  854. joins are created as LOUTER if the join is nullable.
  855. """
  856. if reuse_with_filtered_relation and reuse:
  857. reuse_aliases = [
  858. a for a, j in self.alias_map.items()
  859. if a in reuse and j.equals(join, with_filtered_relation=False)
  860. ]
  861. else:
  862. reuse_aliases = [
  863. a for a, j in self.alias_map.items()
  864. if (reuse is None or a in reuse) and j == join
  865. ]
  866. if reuse_aliases:
  867. if join.table_alias in reuse_aliases:
  868. reuse_alias = join.table_alias
  869. else:
  870. # Reuse the most recent alias of the joined table
  871. # (a many-to-many relation may be joined multiple times).
  872. reuse_alias = reuse_aliases[-1]
  873. self.ref_alias(reuse_alias)
  874. return reuse_alias
  875. # No reuse is possible, so we need a new alias.
  876. alias, _ = self.table_alias(join.table_name, create=True, filtered_relation=join.filtered_relation)
  877. if join.join_type:
  878. if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable:
  879. join_type = LOUTER
  880. else:
  881. join_type = INNER
  882. join.join_type = join_type
  883. join.table_alias = alias
  884. self.alias_map[alias] = join
  885. return alias
  886. def join_parent_model(self, opts, model, alias, seen):
  887. """
  888. Make sure the given 'model' is joined in the query. If 'model' isn't
  889. a parent of 'opts' or if it is None this method is a no-op.
  890. The 'alias' is the root alias for starting the join, 'seen' is a dict
  891. of model -> alias of existing joins. It must also contain a mapping
  892. of None -> some alias. This will be returned in the no-op case.
  893. """
  894. if model in seen:
  895. return seen[model]
  896. chain = opts.get_base_chain(model)
  897. if not chain:
  898. return alias
  899. curr_opts = opts
  900. for int_model in chain:
  901. if int_model in seen:
  902. curr_opts = int_model._meta
  903. alias = seen[int_model]
  904. continue
  905. # Proxy model have elements in base chain
  906. # with no parents, assign the new options
  907. # object and skip to the next base in that
  908. # case
  909. if not curr_opts.parents[int_model]:
  910. curr_opts = int_model._meta
  911. continue
  912. link_field = curr_opts.get_ancestor_link(int_model)
  913. join_info = self.setup_joins([link_field.name], curr_opts, alias)
  914. curr_opts = int_model._meta
  915. alias = seen[int_model] = join_info.joins[-1]
  916. return alias or seen[None]
  917. def add_annotation(self, annotation, alias, is_summary=False):
  918. """Add a single annotation expression to the Query."""
  919. annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None,
  920. summarize=is_summary)
  921. self.append_annotation_mask([alias])
  922. self.annotations[alias] = annotation
  923. def resolve_expression(self, query, *args, **kwargs):
  924. clone = self.clone()
  925. # Subqueries need to use a different set of aliases than the outer query.
  926. clone.bump_prefix(query)
  927. clone.subquery = True
  928. # It's safe to drop ordering if the queryset isn't using slicing,
  929. # distinct(*fields) or select_for_update().
  930. if (self.low_mark == 0 and self.high_mark is None and
  931. not self.distinct_fields and
  932. not self.select_for_update):
  933. clone.clear_ordering(True)
  934. clone.where.resolve_expression(query, *args, **kwargs)
  935. for key, value in clone.annotations.items():
  936. resolved = value.resolve_expression(query, *args, **kwargs)
  937. if hasattr(resolved, 'external_aliases'):
  938. resolved.external_aliases.update(clone.external_aliases)
  939. clone.annotations[key] = resolved
  940. # Outer query's aliases are considered external.
  941. for alias, table in query.alias_map.items():
  942. clone.external_aliases[alias] = (
  943. (isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias) or
  944. (isinstance(table, BaseTable) and table.table_name != table.table_alias)
  945. )
  946. return clone
  947. def get_external_cols(self):
  948. exprs = chain(self.annotations.values(), self.where.children)
  949. return [
  950. col for col in self._gen_cols(exprs)
  951. if col.alias in self.external_aliases
  952. ]
  953. def as_sql(self, compiler, connection):
  954. sql, params = self.get_compiler(connection=connection).as_sql()
  955. if self.subquery:
  956. sql = '(%s)' % sql
  957. return sql, params
  958. def resolve_lookup_value(self, value, can_reuse, allow_joins, simple_col):
  959. if hasattr(value, 'resolve_expression'):
  960. kwargs = {'reuse': can_reuse, 'allow_joins': allow_joins}
  961. if isinstance(value, F):
  962. kwargs['simple_col'] = simple_col
  963. value = value.resolve_expression(self, **kwargs)
  964. elif isinstance(value, (list, tuple)):
  965. # The items of the iterable may be expressions and therefore need
  966. # to be resolved independently.
  967. return type(value)(
  968. self.resolve_lookup_value(sub_value, can_reuse, allow_joins, simple_col)
  969. for sub_value in value
  970. )
  971. return value
  972. def solve_lookup_type(self, lookup):
  973. """
  974. Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains').
  975. """
  976. lookup_splitted = lookup.split(LOOKUP_SEP)
  977. if self.annotations:
  978. expression, expression_lookups = refs_expression(lookup_splitted, self.annotations)
  979. if expression:
  980. return expression_lookups, (), expression
  981. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  982. field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
  983. if len(lookup_parts) > 1 and not field_parts:
  984. raise FieldError(
  985. 'Invalid lookup "%s" for model %s".' %
  986. (lookup, self.get_meta().model.__name__)
  987. )
  988. return lookup_parts, field_parts, False
  989. def check_query_object_type(self, value, opts, field):
  990. """
  991. Check whether the object passed while querying is of the correct type.
  992. If not, raise a ValueError specifying the wrong object.
  993. """
  994. if hasattr(value, '_meta'):
  995. if not check_rel_lookup_compatibility(value._meta.model, opts, field):
  996. raise ValueError(
  997. 'Cannot query "%s": Must be "%s" instance.' %
  998. (value, opts.object_name))
  999. def check_related_objects(self, field, value, opts):
  1000. """Check the type of object passed to query relations."""
  1001. if field.is_relation:
  1002. # Check that the field and the queryset use the same model in a
  1003. # query like .filter(author=Author.objects.all()). For example, the
  1004. # opts would be Author's (from the author field) and value.model
  1005. # would be Author.objects.all() queryset's .model (Author also).
  1006. # The field is the related field on the lhs side.
  1007. if (isinstance(value, Query) and not value.has_select_fields and
  1008. not check_rel_lookup_compatibility(value.model, opts, field)):
  1009. raise ValueError(
  1010. 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' %
  1011. (value.model._meta.object_name, opts.object_name)
  1012. )
  1013. elif hasattr(value, '_meta'):
  1014. self.check_query_object_type(value, opts, field)
  1015. elif hasattr(value, '__iter__'):
  1016. for v in value:
  1017. self.check_query_object_type(v, opts, field)
  1018. def check_filterable(self, expression):
  1019. """Raise an error if expression cannot be used in a WHERE clause."""
  1020. if not getattr(expression, 'filterable', 'True'):
  1021. raise NotSupportedError(
  1022. expression.__class__.__name__ + ' is disallowed in the filter '
  1023. 'clause.'
  1024. )
  1025. if hasattr(expression, 'get_source_expressions'):
  1026. for expr in expression.get_source_expressions():
  1027. self.check_filterable(expr)
  1028. def build_lookup(self, lookups, lhs, rhs):
  1029. """
  1030. Try to extract transforms and lookup from given lhs.
  1031. The lhs value is something that works like SQLExpression.
  1032. The rhs value is what the lookup is going to compare against.
  1033. The lookups is a list of names to extract using get_lookup()
  1034. and get_transform().
  1035. """
  1036. # __exact is the default lookup if one isn't given.
  1037. *transforms, lookup_name = lookups or ['exact']
  1038. for name in transforms:
  1039. lhs = self.try_transform(lhs, name)
  1040. # First try get_lookup() so that the lookup takes precedence if the lhs
  1041. # supports both transform and lookup for the name.
  1042. lookup_class = lhs.get_lookup(lookup_name)
  1043. if not lookup_class:
  1044. if lhs.field.is_relation:
  1045. raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))
  1046. # A lookup wasn't found. Try to interpret the name as a transform
  1047. # and do an Exact lookup against it.
  1048. lhs = self.try_transform(lhs, lookup_name)
  1049. lookup_name = 'exact'
  1050. lookup_class = lhs.get_lookup(lookup_name)
  1051. if not lookup_class:
  1052. return
  1053. lookup = lookup_class(lhs, rhs)
  1054. # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
  1055. # uses of None as a query value unless the lookup supports it.
  1056. if lookup.rhs is None and not lookup.can_use_none_as_rhs:
  1057. if lookup_name not in ('exact', 'iexact'):
  1058. raise ValueError("Cannot use None as a query value")
  1059. return lhs.get_lookup('isnull')(lhs, True)
  1060. # For Oracle '' is equivalent to null. The check must be done at this
  1061. # stage because join promotion can't be done in the compiler. Using
  1062. # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.
  1063. # A similar thing is done in is_nullable(), too.
  1064. if (connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
  1065. lookup_name == 'exact' and lookup.rhs == ''):
  1066. return lhs.get_lookup('isnull')(lhs, True)
  1067. return lookup
  1068. def try_transform(self, lhs, name):
  1069. """
  1070. Helper method for build_lookup(). Try to fetch and initialize
  1071. a transform for name parameter from lhs.
  1072. """
  1073. transform_class = lhs.get_transform(name)
  1074. if transform_class:
  1075. return transform_class(lhs)
  1076. else:
  1077. output_field = lhs.output_field.__class__
  1078. suggested_lookups = difflib.get_close_matches(name, output_field.get_lookups())
  1079. if suggested_lookups:
  1080. suggestion = ', perhaps you meant %s?' % ' or '.join(suggested_lookups)
  1081. else:
  1082. suggestion = '.'
  1083. raise FieldError(
  1084. "Unsupported lookup '%s' for %s or join on the field not "
  1085. "permitted%s" % (name, output_field.__name__, suggestion)
  1086. )
  1087. def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
  1088. can_reuse=None, allow_joins=True, split_subq=True,
  1089. reuse_with_filtered_relation=False, simple_col=False,
  1090. check_filterable=True):
  1091. """
  1092. Build a WhereNode for a single filter clause but don't add it
  1093. to this Query. Query.add_q() will then add this filter to the where
  1094. Node.
  1095. The 'branch_negated' tells us if the current branch contains any
  1096. negations. This will be used to determine if subqueries are needed.
  1097. The 'current_negated' is used to determine if the current filter is
  1098. negated or not and this will be used to determine if IS NULL filtering
  1099. is needed.
  1100. The difference between current_negated and branch_negated is that
  1101. branch_negated is set on first negation, but current_negated is
  1102. flipped for each negation.
  1103. Note that add_filter will not do any negating itself, that is done
  1104. upper in the code by add_q().
  1105. The 'can_reuse' is a set of reusable joins for multijoins.
  1106. If 'reuse_with_filtered_relation' is True, then only joins in can_reuse
  1107. will be reused.
  1108. The method will create a filter clause that can be added to the current
  1109. query. However, if the filter isn't added to the query then the caller
  1110. is responsible for unreffing the joins used.
  1111. """
  1112. if isinstance(filter_expr, dict):
  1113. raise FieldError("Cannot parse keyword query as dict")
  1114. if hasattr(filter_expr, 'resolve_expression') and getattr(filter_expr, 'conditional', False):
  1115. if connections[DEFAULT_DB_ALIAS].ops.conditional_expression_supported_in_where_clause(filter_expr):
  1116. condition = filter_expr.resolve_expression(self)
  1117. else:
  1118. # Expression is not supported in the WHERE clause, add
  1119. # comparison with True.
  1120. condition = self.build_lookup(['exact'], filter_expr.resolve_expression(self), True)
  1121. clause = self.where_class()
  1122. clause.add(condition, AND)
  1123. return clause, []
  1124. arg, value = filter_expr
  1125. if not arg:
  1126. raise FieldError("Cannot parse keyword query %r" % arg)
  1127. lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  1128. if check_filterable:
  1129. self.check_filterable(reffed_expression)
  1130. if not allow_joins and len(parts) > 1:
  1131. raise FieldError("Joined field references are not permitted in this query")
  1132. pre_joins = self.alias_refcount.copy()
  1133. value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col)
  1134. used_joins = {k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0)}
  1135. if check_filterable:
  1136. self.check_filterable(value)
  1137. clause = self.where_class()
  1138. if reffed_expression:
  1139. condition = self.build_lookup(lookups, reffed_expression, value)
  1140. clause.add(condition, AND)
  1141. return clause, []
  1142. opts = self.get_meta()
  1143. alias = self.get_initial_alias()
  1144. allow_many = not branch_negated or not split_subq
  1145. try:
  1146. join_info = self.setup_joins(
  1147. parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many,
  1148. reuse_with_filtered_relation=reuse_with_filtered_relation,
  1149. )
  1150. # Prevent iterator from being consumed by check_related_objects()
  1151. if isinstance(value, Iterator):
  1152. value = list(value)
  1153. self.check_related_objects(join_info.final_field, value, join_info.opts)
  1154. # split_exclude() needs to know which joins were generated for the
  1155. # lookup parts
  1156. self._lookup_joins = join_info.joins
  1157. except MultiJoin as e:
  1158. return self.split_exclude(filter_expr, can_reuse, e.names_with_path)
  1159. # Update used_joins before trimming since they are reused to determine
  1160. # which joins could be later promoted to INNER.
  1161. used_joins.update(join_info.joins)
  1162. targets, alias, join_list = self.trim_joins(join_info.targets, join_info.joins, join_info.path)
  1163. if can_reuse is not None:
  1164. can_reuse.update(join_list)
  1165. if join_info.final_field.is_relation:
  1166. # No support for transforms for relational fields
  1167. num_lookups = len(lookups)
  1168. if num_lookups > 1:
  1169. raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0]))
  1170. if len(targets) == 1:
  1171. col = _get_col(targets[0], join_info.final_field, alias, simple_col)
  1172. else:
  1173. col = MultiColSource(alias, targets, join_info.targets, join_info.final_field)
  1174. else:
  1175. col = _get_col(targets[0], join_info.final_field, alias, simple_col)
  1176. condition = self.build_lookup(lookups, col, value)
  1177. lookup_type = condition.lookup_name
  1178. clause.add(condition, AND)
  1179. require_outer = lookup_type == 'isnull' and condition.rhs is True and not current_negated
  1180. if current_negated and (lookup_type != 'isnull' or condition.rhs is False) and condition.rhs is not None:
  1181. require_outer = True
  1182. if (lookup_type != 'isnull' and (
  1183. self.is_nullable(targets[0]) or
  1184. self.alias_map[join_list[-1]].join_type == LOUTER)):
  1185. # The condition added here will be SQL like this:
  1186. # NOT (col IS NOT NULL), where the first NOT is added in
  1187. # upper layers of code. The reason for addition is that if col
  1188. # is null, then col != someval will result in SQL "unknown"
  1189. # which isn't the same as in Python. The Python None handling
  1190. # is wanted, and it can be gotten by
  1191. # (col IS NULL OR col != someval)
  1192. # <=>
  1193. # NOT (col IS NOT NULL AND col = someval).
  1194. lookup_class = targets[0].get_lookup('isnull')
  1195. col = _get_col(targets[0], join_info.targets[0], alias, simple_col)
  1196. clause.add(lookup_class(col, False), AND)
  1197. return clause, used_joins if not require_outer else ()
  1198. def add_filter(self, filter_clause):
  1199. self.add_q(Q(**{filter_clause[0]: filter_clause[1]}))
  1200. def add_q(self, q_object):
  1201. """
  1202. A preprocessor for the internal _add_q(). Responsible for doing final
  1203. join promotion.
  1204. """
  1205. # For join promotion this case is doing an AND for the added q_object
  1206. # and existing conditions. So, any existing inner join forces the join
  1207. # type to remain inner. Existing outer joins can however be demoted.
  1208. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
  1209. # rel_a doesn't produce any rows, then the whole condition must fail.
  1210. # So, demotion is OK.
  1211. existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}
  1212. clause, _ = self._add_q(q_object, self.used_aliases)
  1213. if clause:
  1214. self.where.add(clause, AND)
  1215. self.demote_joins(existing_inner)
  1216. def build_where(self, q_object):
  1217. return self._add_q(q_object, used_aliases=set(), allow_joins=False, simple_col=True)[0]
  1218. def _add_q(self, q_object, used_aliases, branch_negated=False,
  1219. current_negated=False, allow_joins=True, split_subq=True,
  1220. simple_col=False, check_filterable=True):
  1221. """Add a Q-object to the current filter."""
  1222. connector = q_object.connector
  1223. current_negated = current_negated ^ q_object.negated
  1224. branch_negated = branch_negated or q_object.negated
  1225. target_clause = self.where_class(connector=connector,
  1226. negated=q_object.negated)
  1227. joinpromoter = JoinPromoter(q_object.connector, len(q_object.children), current_negated)
  1228. for child in q_object.children:
  1229. if isinstance(child, Node):
  1230. child_clause, needed_inner = self._add_q(
  1231. child, used_aliases, branch_negated,
  1232. current_negated, allow_joins, split_subq, simple_col,
  1233. check_filterable,
  1234. )
  1235. joinpromoter.add_votes(needed_inner)
  1236. else:
  1237. child_clause, needed_inner = self.build_filter(
  1238. child, can_reuse=used_aliases, branch_negated=branch_negated,
  1239. current_negated=current_negated, allow_joins=allow_joins,
  1240. split_subq=split_subq, simple_col=simple_col,
  1241. check_filterable=check_filterable,
  1242. )
  1243. joinpromoter.add_votes(needed_inner)
  1244. if child_clause:
  1245. target_clause.add(child_clause, connector)
  1246. needed_inner = joinpromoter.update_join_types(self)
  1247. return target_clause, needed_inner
  1248. def build_filtered_relation_q(self, q_object, reuse, branch_negated=False, current_negated=False):
  1249. """Add a FilteredRelation object to the current filter."""
  1250. connector = q_object.connector
  1251. current_negated ^= q_object.negated
  1252. branch_negated = branch_negated or q_object.negated
  1253. target_clause = self.where_class(connector=connector, negated=q_object.negated)
  1254. for child in q_object.children:
  1255. if isinstance(child, Node):
  1256. child_clause = self.build_filtered_relation_q(
  1257. child, reuse=reuse, branch_negated=branch_negated,
  1258. current_negated=current_negated,
  1259. )
  1260. else:
  1261. child_clause, _ = self.build_filter(
  1262. child, can_reuse=reuse, branch_negated=branch_negated,
  1263. current_negated=current_negated,
  1264. allow_joins=True, split_subq=False,
  1265. reuse_with_filtered_relation=True,
  1266. )
  1267. target_clause.add(child_clause, connector)
  1268. return target_clause
  1269. def add_filtered_relation(self, filtered_relation, alias):
  1270. filtered_relation.alias = alias
  1271. lookups = dict(get_children_from_q(filtered_relation.condition))
  1272. for lookup in chain((filtered_relation.relation_name,), lookups):
  1273. lookup_parts, field_parts, _ = self.solve_lookup_type(lookup)
  1274. shift = 2 if not lookup_parts else 1
  1275. if len(field_parts) > (shift + len(lookup_parts)):
  1276. raise ValueError(
  1277. "FilteredRelation's condition doesn't support nested "
  1278. "relations (got %r)." % lookup
  1279. )
  1280. self._filtered_relations[filtered_relation.alias] = filtered_relation
  1281. def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
  1282. """
  1283. Walk the list of names and turns them into PathInfo tuples. A single
  1284. name in 'names' can generate multiple PathInfos (m2m, for example).
  1285. 'names' is the path of names to travel, 'opts' is the model Options we
  1286. start the name resolving from, 'allow_many' is as for setup_joins().
  1287. If fail_on_missing is set to True, then a name that can't be resolved
  1288. will generate a FieldError.
  1289. Return a list of PathInfo tuples. In addition return the final field
  1290. (the last used join field) and target (which is a field guaranteed to
  1291. contain the same value as the final field). Finally, return those names
  1292. that weren't found (which are likely transforms and the final lookup).
  1293. """
  1294. path, names_with_path = [], []
  1295. for pos, name in enumerate(names):
  1296. cur_names_with_path = (name, [])
  1297. if name == 'pk':
  1298. name = opts.pk.name
  1299. field = None
  1300. filtered_relation = None
  1301. try:
  1302. field = opts.get_field(name)
  1303. except FieldDoesNotExist:
  1304. if name in self.annotation_select:
  1305. field = self.annotation_select[name].output_field
  1306. elif name in self._filtered_relations and pos == 0:
  1307. filtered_relation = self._filtered_relations[name]
  1308. field = opts.get_field(filtered_relation.relation_name)
  1309. if field is not None:
  1310. # Fields that contain one-to-many relations with a generic
  1311. # model (like a GenericForeignKey) cannot generate reverse
  1312. # relations and therefore cannot be used for reverse querying.
  1313. if field.is_relation and not field.related_model:
  1314. raise FieldError(
  1315. "Field %r does not generate an automatic reverse "
  1316. "relation and therefore cannot be used for reverse "
  1317. "querying. If it is a GenericForeignKey, consider "
  1318. "adding a GenericRelation." % name
  1319. )
  1320. try:
  1321. model = field.model._meta.concrete_model
  1322. except AttributeError:
  1323. # QuerySet.annotate() may introduce fields that aren't
  1324. # attached to a model.
  1325. model = None
  1326. else:
  1327. # We didn't find the current field, so move position back
  1328. # one step.
  1329. pos -= 1
  1330. if pos == -1 or fail_on_missing:
  1331. available = sorted([
  1332. *get_field_names_from_opts(opts),
  1333. *self.annotation_select,
  1334. *self._filtered_relations,
  1335. ])
  1336. raise FieldError("Cannot resolve keyword '%s' into field. "
  1337. "Choices are: %s" % (name, ", ".join(available)))
  1338. break
  1339. # Check if we need any joins for concrete inheritance cases (the
  1340. # field lives in parent, but we are currently in one of its
  1341. # children)
  1342. if model is not opts.model:
  1343. path_to_parent = opts.get_path_to_parent(model)
  1344. if path_to_parent:
  1345. path.extend(path_to_parent)
  1346. cur_names_with_path[1].extend(path_to_parent)
  1347. opts = path_to_parent[-1].to_opts
  1348. if hasattr(field, 'get_path_info'):
  1349. pathinfos = field.get_path_info(filtered_relation)
  1350. if not allow_many:
  1351. for inner_pos, p in enumerate(pathinfos):
  1352. if p.m2m:
  1353. cur_names_with_path[1].extend(pathinfos[0:inner_pos + 1])
  1354. names_with_path.append(cur_names_with_path)
  1355. raise MultiJoin(pos + 1, names_with_path)
  1356. last = pathinfos[-1]
  1357. path.extend(pathinfos)
  1358. final_field = last.join_field
  1359. opts = last.to_opts
  1360. targets = last.target_fields
  1361. cur_names_with_path[1].extend(pathinfos)
  1362. names_with_path.append(cur_names_with_path)
  1363. else:
  1364. # Local non-relational field.
  1365. final_field = field
  1366. targets = (field,)
  1367. if fail_on_missing and pos + 1 != len(names):
  1368. raise FieldError(
  1369. "Cannot resolve keyword %r into field. Join on '%s'"
  1370. " not permitted." % (names[pos + 1], name))
  1371. break
  1372. return path, final_field, targets, names[pos + 1:]
  1373. def setup_joins(self, names, opts, alias, can_reuse=None, allow_many=True,
  1374. reuse_with_filtered_relation=False):
  1375. """
  1376. Compute the necessary table joins for the passage through the fields
  1377. given in 'names'. 'opts' is the Options class for the current model
  1378. (which gives the table we are starting from), 'alias' is the alias for
  1379. the table to start the joining from.
  1380. The 'can_reuse' defines the reverse foreign key joins we can reuse. It
  1381. can be None in which case all joins are reusable or a set of aliases
  1382. that can be reused. Note that non-reverse foreign keys are always
  1383. reusable when using setup_joins().
  1384. The 'reuse_with_filtered_relation' can be used to force 'can_reuse'
  1385. parameter and force the relation on the given connections.
  1386. If 'allow_many' is False, then any reverse foreign key seen will
  1387. generate a MultiJoin exception.
  1388. Return the final field involved in the joins, the target field (used
  1389. for any 'where' constraint), the final 'opts' value, the joins, the
  1390. field path traveled to generate the joins, and a transform function
  1391. that takes a field and alias and is equivalent to `field.get_col(alias)`
  1392. in the simple case but wraps field transforms if they were included in
  1393. names.
  1394. The target field is the field containing the concrete value. Final
  1395. field can be something different, for example foreign key pointing to
  1396. that value. Final field is needed for example in some value
  1397. conversions (convert 'obj' in fk__id=obj to pk val using the foreign
  1398. key field for example).
  1399. """
  1400. joins = [alias]
  1401. # The transform can't be applied yet, as joins must be trimmed later.
  1402. # To avoid making every caller of this method look up transforms
  1403. # directly, compute transforms here and create a partial that converts
  1404. # fields to the appropriate wrapped version.
  1405. def final_transformer(field, alias):
  1406. return field.get_col(alias)
  1407. # Try resolving all the names as fields first. If there's an error,
  1408. # treat trailing names as lookups until a field can be resolved.
  1409. last_field_exception = None
  1410. for pivot in range(len(names), 0, -1):
  1411. try:
  1412. path, final_field, targets, rest = self.names_to_path(
  1413. names[:pivot], opts, allow_many, fail_on_missing=True,
  1414. )
  1415. except FieldError as exc:
  1416. if pivot == 1:
  1417. # The first item cannot be a lookup, so it's safe
  1418. # to raise the field error here.
  1419. raise
  1420. else:
  1421. last_field_exception = exc
  1422. else:
  1423. # The transforms are the remaining items that couldn't be
  1424. # resolved into fields.
  1425. transforms = names[pivot:]
  1426. break
  1427. for name in transforms:
  1428. def transform(field, alias, *, name, previous):
  1429. try:
  1430. wrapped = previous(field, alias)
  1431. return self.try_transform(wrapped, name)
  1432. except FieldError:
  1433. # FieldError is raised if the transform doesn't exist.
  1434. if isinstance(final_field, Field) and last_field_exception:
  1435. raise last_field_exception
  1436. else:
  1437. raise
  1438. final_transformer = functools.partial(transform, name=name, previous=final_transformer)
  1439. # Then, add the path to the query's joins. Note that we can't trim
  1440. # joins at this stage - we will need the information about join type
  1441. # of the trimmed joins.
  1442. for join in path:
  1443. if join.filtered_relation:
  1444. filtered_relation = join.filtered_relation.clone()
  1445. table_alias = filtered_relation.alias
  1446. else:
  1447. filtered_relation = None
  1448. table_alias = None
  1449. opts = join.to_opts
  1450. if join.direct:
  1451. nullable = self.is_nullable(join.join_field)
  1452. else:
  1453. nullable = True
  1454. connection = Join(
  1455. opts.db_table, alias, table_alias, INNER, join.join_field,
  1456. nullable, filtered_relation=filtered_relation,
  1457. )
  1458. reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None
  1459. alias = self.join(
  1460. connection, reuse=reuse,
  1461. reuse_with_filtered_relation=reuse_with_filtered_relation,
  1462. )
  1463. joins.append(alias)
  1464. if filtered_relation:
  1465. filtered_relation.path = joins[:]
  1466. return JoinInfo(final_field, targets, opts, joins, path, final_transformer)
  1467. def trim_joins(self, targets, joins, path):
  1468. """
  1469. The 'target' parameter is the final field being joined to, 'joins'
  1470. is the full list of join aliases. The 'path' contain the PathInfos
  1471. used to create the joins.
  1472. Return the final target field and table alias and the new active
  1473. joins.
  1474. Always trim any direct join if the target column is already in the
  1475. previous table. Can't trim reverse joins as it's unknown if there's
  1476. anything on the other side of the join.
  1477. """
  1478. joins = joins[:]
  1479. for pos, info in enumerate(reversed(path)):
  1480. if len(joins) == 1 or not info.direct:
  1481. break
  1482. if info.filtered_relation:
  1483. break
  1484. join_targets = {t.column for t in info.join_field.foreign_related_fields}
  1485. cur_targets = {t.column for t in targets}
  1486. if not cur_targets.issubset(join_targets):
  1487. break
  1488. targets_dict = {r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets}
  1489. targets = tuple(targets_dict[t.column] for t in targets)
  1490. self.unref_alias(joins.pop())
  1491. return targets, joins[-1], joins
  1492. @classmethod
  1493. def _gen_cols(cls, exprs):
  1494. for expr in exprs:
  1495. if isinstance(expr, Col):
  1496. yield expr
  1497. else:
  1498. yield from cls._gen_cols(expr.get_source_expressions())
  1499. @classmethod
  1500. def _gen_col_aliases(cls, exprs):
  1501. yield from (expr.alias for expr in cls._gen_cols(exprs))
  1502. def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False, simple_col=False):
  1503. if not allow_joins and LOOKUP_SEP in name:
  1504. raise FieldError("Joined field references are not permitted in this query")
  1505. annotation = self.annotations.get(name)
  1506. if annotation is not None:
  1507. if not allow_joins:
  1508. for alias in self._gen_col_aliases([annotation]):
  1509. if isinstance(self.alias_map[alias], Join):
  1510. raise FieldError(
  1511. 'Joined field references are not permitted in '
  1512. 'this query'
  1513. )
  1514. if summarize:
  1515. # Summarize currently means we are doing an aggregate() query
  1516. # which is executed as a wrapped subquery if any of the
  1517. # aggregate() elements reference an existing annotation. In
  1518. # that case we need to return a Ref to the subquery's annotation.
  1519. return Ref(name, self.annotation_select[name])
  1520. else:
  1521. return annotation
  1522. else:
  1523. field_list = name.split(LOOKUP_SEP)
  1524. join_info = self.setup_joins(field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse)
  1525. targets, final_alias, join_list = self.trim_joins(join_info.targets, join_info.joins, join_info.path)
  1526. if not allow_joins and len(join_list) > 1:
  1527. raise FieldError('Joined field references are not permitted in this query')
  1528. if len(targets) > 1:
  1529. raise FieldError("Referencing multicolumn fields with F() objects "
  1530. "isn't supported")
  1531. # Verify that the last lookup in name is a field or a transform:
  1532. # transform_function() raises FieldError if not.
  1533. join_info.transform_function(targets[0], final_alias)
  1534. if reuse is not None:
  1535. reuse.update(join_list)
  1536. col = _get_col(targets[0], join_info.targets[0], join_list[-1], simple_col)
  1537. return col
  1538. def split_exclude(self, filter_expr, can_reuse, names_with_path):
  1539. """
  1540. When doing an exclude against any kind of N-to-many relation, we need
  1541. to use a subquery. This method constructs the nested query, given the
  1542. original exclude filter (filter_expr) and the portion up to the first
  1543. N-to-many relation field.
  1544. For example, if the origin filter is ~Q(child__name='foo'), filter_expr
  1545. is ('child__name', 'foo') and can_reuse is a set of joins usable for
  1546. filters in the original query.
  1547. We will turn this into equivalent of:
  1548. WHERE NOT (pk IN (SELECT parent_id FROM thetable
  1549. WHERE name = 'foo' AND parent_id IS NOT NULL))
  1550. It might be worth it to consider using WHERE NOT EXISTS as that has
  1551. saner null handling, and is easier for the backend's optimizer to
  1552. handle.
  1553. """
  1554. filter_lhs, filter_rhs = filter_expr
  1555. if isinstance(filter_rhs, OuterRef):
  1556. filter_expr = (filter_lhs, OuterRef(filter_rhs))
  1557. elif isinstance(filter_rhs, F):
  1558. filter_expr = (filter_lhs, OuterRef(filter_rhs.name))
  1559. # Generate the inner query.
  1560. query = Query(self.model)
  1561. query._filtered_relations = self._filtered_relations
  1562. query.add_filter(filter_expr)
  1563. query.clear_ordering(True)
  1564. # Try to have as simple as possible subquery -> trim leading joins from
  1565. # the subquery.
  1566. trimmed_prefix, contains_louter = query.trim_start(names_with_path)
  1567. # Add extra check to make sure the selected field will not be null
  1568. # since we are adding an IN <subquery> clause. This prevents the
  1569. # database from tripping over IN (...,NULL,...) selects and returning
  1570. # nothing
  1571. col = query.select[0]
  1572. select_field = col.target
  1573. alias = col.alias
  1574. if self.is_nullable(select_field):
  1575. lookup_class = select_field.get_lookup('isnull')
  1576. lookup = lookup_class(select_field.get_col(alias), False)
  1577. query.where.add(lookup, AND)
  1578. if alias in can_reuse:
  1579. pk = select_field.model._meta.pk
  1580. # Need to add a restriction so that outer query's filters are in effect for
  1581. # the subquery, too.
  1582. query.bump_prefix(self)
  1583. lookup_class = select_field.get_lookup('exact')
  1584. # Note that the query.select[0].alias is different from alias
  1585. # due to bump_prefix above.
  1586. lookup = lookup_class(pk.get_col(query.select[0].alias),
  1587. pk.get_col(alias))
  1588. query.where.add(lookup, AND)
  1589. query.external_aliases[alias] = True
  1590. condition, needed_inner = self.build_filter(
  1591. ('%s__in' % trimmed_prefix, query),
  1592. current_negated=True, branch_negated=True, can_reuse=can_reuse)
  1593. if contains_louter:
  1594. or_null_condition, _ = self.build_filter(
  1595. ('%s__isnull' % trimmed_prefix, True),
  1596. current_negated=True, branch_negated=True, can_reuse=can_reuse)
  1597. condition.add(or_null_condition, OR)
  1598. # Note that the end result will be:
  1599. # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL.
  1600. # This might look crazy but due to how IN works, this seems to be
  1601. # correct. If the IS NOT NULL check is removed then outercol NOT
  1602. # IN will return UNKNOWN. If the IS NULL check is removed, then if
  1603. # outercol IS NULL we will not match the row.
  1604. return condition, needed_inner
  1605. def set_empty(self):
  1606. self.where.add(NothingNode(), AND)
  1607. def is_empty(self):
  1608. return any(isinstance(c, NothingNode) for c in self.where.children)
  1609. def set_limits(self, low=None, high=None):
  1610. """
  1611. Adjust the limits on the rows retrieved. Use low/high to set these,
  1612. as it makes it more Pythonic to read and write. When the SQL query is
  1613. created, convert them to the appropriate offset and limit values.
  1614. Apply any limits passed in here to the existing constraints. Add low
  1615. to the current low value and clamp both to any existing high value.
  1616. """
  1617. if high is not None:
  1618. if self.high_mark is not None:
  1619. self.high_mark = min(self.high_mark, self.low_mark + high)
  1620. else:
  1621. self.high_mark = self.low_mark + high
  1622. if low is not None:
  1623. if self.high_mark is not None:
  1624. self.low_mark = min(self.high_mark, self.low_mark + low)
  1625. else:
  1626. self.low_mark = self.low_mark + low
  1627. if self.low_mark == self.high_mark:
  1628. self.set_empty()
  1629. def clear_limits(self):
  1630. """Clear any existing limits."""
  1631. self.low_mark, self.high_mark = 0, None
  1632. @property
  1633. def is_sliced(self):
  1634. return self.low_mark != 0 or self.high_mark is not None
  1635. def has_limit_one(self):
  1636. return self.high_mark is not None and (self.high_mark - self.low_mark) == 1
  1637. def can_filter(self):
  1638. """
  1639. Return True if adding filters to this instance is still possible.
  1640. Typically, this means no limits or offsets have been put on the results.
  1641. """
  1642. return not self.is_sliced
  1643. def clear_select_clause(self):
  1644. """Remove all fields from SELECT clause."""
  1645. self.select = ()
  1646. self.default_cols = False
  1647. self.select_related = False
  1648. self.set_extra_mask(())
  1649. self.set_annotation_mask(())
  1650. def clear_select_fields(self):
  1651. """
  1652. Clear the list of fields to select (but not extra_select columns).
  1653. Some queryset types completely replace any existing list of select
  1654. columns.
  1655. """
  1656. self.select = ()
  1657. self.values_select = ()
  1658. def add_select_col(self, col):
  1659. self.select += col,
  1660. self.values_select += col.output_field.name,
  1661. def set_select(self, cols):
  1662. self.default_cols = False
  1663. self.select = tuple(cols)
  1664. def add_distinct_fields(self, *field_names):
  1665. """
  1666. Add and resolve the given fields to the query's "distinct on" clause.
  1667. """
  1668. self.distinct_fields = field_names
  1669. self.distinct = True
  1670. def add_fields(self, field_names, allow_m2m=True):
  1671. """
  1672. Add the given (model) fields to the select set. Add the field names in
  1673. the order specified.
  1674. """
  1675. alias = self.get_initial_alias()
  1676. opts = self.get_meta()
  1677. try:
  1678. cols = []
  1679. for name in field_names:
  1680. # Join promotion note - we must not remove any rows here, so
  1681. # if there is no existing joins, use outer join.
  1682. join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
  1683. targets, final_alias, joins = self.trim_joins(
  1684. join_info.targets,
  1685. join_info.joins,
  1686. join_info.path,
  1687. )
  1688. for target in targets:
  1689. cols.append(join_info.transform_function(target, final_alias))
  1690. if cols:
  1691. self.set_select(cols)
  1692. except MultiJoin:
  1693. raise FieldError("Invalid field name: '%s'" % name)
  1694. except FieldError:
  1695. if LOOKUP_SEP in name:
  1696. # For lookups spanning over relationships, show the error
  1697. # from the model on which the lookup failed.
  1698. raise
  1699. else:
  1700. names = sorted([
  1701. *get_field_names_from_opts(opts), *self.extra,
  1702. *self.annotation_select, *self._filtered_relations
  1703. ])
  1704. raise FieldError("Cannot resolve keyword %r into field. "
  1705. "Choices are: %s" % (name, ", ".join(names)))
  1706. def add_ordering(self, *ordering):
  1707. """
  1708. Add items from the 'ordering' sequence to the query's "order by"
  1709. clause. These items are either field names (not column names) --
  1710. possibly with a direction prefix ('-' or '?') -- or OrderBy
  1711. expressions.
  1712. If 'ordering' is empty, clear all ordering from the query.
  1713. """
  1714. errors = []
  1715. for item in ordering:
  1716. if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item):
  1717. errors.append(item)
  1718. if getattr(item, 'contains_aggregate', False):
  1719. raise FieldError(
  1720. 'Using an aggregate in order_by() without also including '
  1721. 'it in annotate() is not allowed: %s' % item
  1722. )
  1723. if errors:
  1724. raise FieldError('Invalid order_by arguments: %s' % errors)
  1725. if ordering:
  1726. self.order_by += ordering
  1727. else:
  1728. self.default_ordering = False
  1729. def clear_ordering(self, force_empty):
  1730. """
  1731. Remove any ordering settings. If 'force_empty' is True, there will be
  1732. no ordering in the resulting query (not even the model's default).
  1733. """
  1734. self.order_by = ()
  1735. self.extra_order_by = ()
  1736. if force_empty:
  1737. self.default_ordering = False
  1738. def set_group_by(self, allow_aliases=True):
  1739. """
  1740. Expand the GROUP BY clause required by the query.
  1741. This will usually be the set of all non-aggregate fields in the
  1742. return data. If the database backend supports grouping by the
  1743. primary key, and the query would be equivalent, the optimization
  1744. will be made automatically.
  1745. """
  1746. group_by = list(self.select)
  1747. if self.annotation_select:
  1748. for alias, annotation in self.annotation_select.items():
  1749. try:
  1750. inspect.getcallargs(annotation.get_group_by_cols, alias=alias)
  1751. except TypeError:
  1752. annotation_class = annotation.__class__
  1753. msg = (
  1754. '`alias=None` must be added to the signature of '
  1755. '%s.%s.get_group_by_cols().'
  1756. ) % (annotation_class.__module__, annotation_class.__qualname__)
  1757. warnings.warn(msg, category=RemovedInDjango40Warning)
  1758. group_by_cols = annotation.get_group_by_cols()
  1759. else:
  1760. if not allow_aliases:
  1761. alias = None
  1762. group_by_cols = annotation.get_group_by_cols(alias=alias)
  1763. group_by.extend(group_by_cols)
  1764. self.group_by = tuple(group_by)
  1765. def add_select_related(self, fields):
  1766. """
  1767. Set up the select_related data structure so that we only select
  1768. certain related models (as opposed to all models, when
  1769. self.select_related=True).
  1770. """
  1771. if isinstance(self.select_related, bool):
  1772. field_dict = {}
  1773. else:
  1774. field_dict = self.select_related
  1775. for field in fields:
  1776. d = field_dict
  1777. for part in field.split(LOOKUP_SEP):
  1778. d = d.setdefault(part, {})
  1779. self.select_related = field_dict
  1780. def add_extra(self, select, select_params, where, params, tables, order_by):
  1781. """
  1782. Add data to the various extra_* attributes for user-created additions
  1783. to the query.
  1784. """
  1785. if select:
  1786. # We need to pair any placeholder markers in the 'select'
  1787. # dictionary with their parameters in 'select_params' so that
  1788. # subsequent updates to the select dictionary also adjust the
  1789. # parameters appropriately.
  1790. select_pairs = {}
  1791. if select_params:
  1792. param_iter = iter(select_params)
  1793. else:
  1794. param_iter = iter([])
  1795. for name, entry in select.items():
  1796. entry = str(entry)
  1797. entry_params = []
  1798. pos = entry.find("%s")
  1799. while pos != -1:
  1800. if pos == 0 or entry[pos - 1] != '%':
  1801. entry_params.append(next(param_iter))
  1802. pos = entry.find("%s", pos + 2)
  1803. select_pairs[name] = (entry, entry_params)
  1804. self.extra.update(select_pairs)
  1805. if where or params:
  1806. self.where.add(ExtraWhere(where, params), AND)
  1807. if tables:
  1808. self.extra_tables += tuple(tables)
  1809. if order_by:
  1810. self.extra_order_by = order_by
  1811. def clear_deferred_loading(self):
  1812. """Remove any fields from the deferred loading set."""
  1813. self.deferred_loading = (frozenset(), True)
  1814. def add_deferred_loading(self, field_names):
  1815. """
  1816. Add the given list of model field names to the set of fields to
  1817. exclude from loading from the database when automatic column selection
  1818. is done. Add the new field names to any existing field names that
  1819. are deferred (or removed from any existing field names that are marked
  1820. as the only ones for immediate loading).
  1821. """
  1822. # Fields on related models are stored in the literal double-underscore
  1823. # format, so that we can use a set datastructure. We do the foo__bar
  1824. # splitting and handling when computing the SQL column names (as part of
  1825. # get_columns()).
  1826. existing, defer = self.deferred_loading
  1827. if defer:
  1828. # Add to existing deferred names.
  1829. self.deferred_loading = existing.union(field_names), True
  1830. else:
  1831. # Remove names from the set of any existing "immediate load" names.
  1832. self.deferred_loading = existing.difference(field_names), False
  1833. def add_immediate_loading(self, field_names):
  1834. """
  1835. Add the given list of model field names to the set of fields to
  1836. retrieve when the SQL is executed ("immediate loading" fields). The
  1837. field names replace any existing immediate loading field names. If
  1838. there are field names already specified for deferred loading, remove
  1839. those names from the new field_names before storing the new names
  1840. for immediate loading. (That is, immediate loading overrides any
  1841. existing immediate values, but respects existing deferrals.)
  1842. """
  1843. existing, defer = self.deferred_loading
  1844. field_names = set(field_names)
  1845. if 'pk' in field_names:
  1846. field_names.remove('pk')
  1847. field_names.add(self.get_meta().pk.name)
  1848. if defer:
  1849. # Remove any existing deferred names from the current set before
  1850. # setting the new names.
  1851. self.deferred_loading = field_names.difference(existing), False
  1852. else:
  1853. # Replace any existing "immediate load" field names.
  1854. self.deferred_loading = frozenset(field_names), False
  1855. def get_loaded_field_names(self):
  1856. """
  1857. If any fields are marked to be deferred, return a dictionary mapping
  1858. models to a set of names in those fields that will be loaded. If a
  1859. model is not in the returned dictionary, none of its fields are
  1860. deferred.
  1861. If no fields are marked for deferral, return an empty dictionary.
  1862. """
  1863. # We cache this because we call this function multiple times
  1864. # (compiler.fill_related_selections, query.iterator)
  1865. try:
  1866. return self._loaded_field_names_cache
  1867. except AttributeError:
  1868. collection = {}
  1869. self.deferred_to_data(collection, self.get_loaded_field_names_cb)
  1870. self._loaded_field_names_cache = collection
  1871. return collection
  1872. def get_loaded_field_names_cb(self, target, model, fields):
  1873. """Callback used by get_deferred_field_names()."""
  1874. target[model] = {f.attname for f in fields}
  1875. def set_annotation_mask(self, names):
  1876. """Set the mask of annotations that will be returned by the SELECT."""
  1877. if names is None:
  1878. self.annotation_select_mask = None
  1879. else:
  1880. self.annotation_select_mask = set(names)
  1881. self._annotation_select_cache = None
  1882. def append_annotation_mask(self, names):
  1883. if self.annotation_select_mask is not None:
  1884. self.set_annotation_mask(self.annotation_select_mask.union(names))
  1885. def set_extra_mask(self, names):
  1886. """
  1887. Set the mask of extra select items that will be returned by SELECT.
  1888. Don't remove them from the Query since they might be used later.
  1889. """
  1890. if names is None:
  1891. self.extra_select_mask = None
  1892. else:
  1893. self.extra_select_mask = set(names)
  1894. self._extra_select_cache = None
  1895. def set_values(self, fields):
  1896. self.select_related = False
  1897. self.clear_deferred_loading()
  1898. self.clear_select_fields()
  1899. if fields:
  1900. field_names = []
  1901. extra_names = []
  1902. annotation_names = []
  1903. if not self.extra and not self.annotations:
  1904. # Shortcut - if there are no extra or annotations, then
  1905. # the values() clause must be just field names.
  1906. field_names = list(fields)
  1907. else:
  1908. self.default_cols = False
  1909. for f in fields:
  1910. if f in self.extra_select:
  1911. extra_names.append(f)
  1912. elif f in self.annotation_select:
  1913. annotation_names.append(f)
  1914. else:
  1915. field_names.append(f)
  1916. self.set_extra_mask(extra_names)
  1917. self.set_annotation_mask(annotation_names)
  1918. else:
  1919. field_names = [f.attname for f in self.model._meta.concrete_fields]
  1920. # Selected annotations must be known before setting the GROUP BY
  1921. # clause.
  1922. if self.group_by is True:
  1923. self.add_fields((f.attname for f in self.model._meta.concrete_fields), False)
  1924. # Disable GROUP BY aliases to avoid orphaning references to the
  1925. # SELECT clause which is about to be cleared.
  1926. self.set_group_by(allow_aliases=False)
  1927. self.clear_select_fields()
  1928. self.values_select = tuple(field_names)
  1929. self.add_fields(field_names, True)
  1930. @property
  1931. def annotation_select(self):
  1932. """
  1933. Return the dictionary of aggregate columns that are not masked and
  1934. should be used in the SELECT clause. Cache this result for performance.
  1935. """
  1936. if self._annotation_select_cache is not None:
  1937. return self._annotation_select_cache
  1938. elif not self.annotations:
  1939. return {}
  1940. elif self.annotation_select_mask is not None:
  1941. self._annotation_select_cache = {
  1942. k: v for k, v in self.annotations.items()
  1943. if k in self.annotation_select_mask
  1944. }
  1945. return self._annotation_select_cache
  1946. else:
  1947. return self.annotations
  1948. @property
  1949. def extra_select(self):
  1950. if self._extra_select_cache is not None:
  1951. return self._extra_select_cache
  1952. if not self.extra:
  1953. return {}
  1954. elif self.extra_select_mask is not None:
  1955. self._extra_select_cache = {
  1956. k: v for k, v in self.extra.items()
  1957. if k in self.extra_select_mask
  1958. }
  1959. return self._extra_select_cache
  1960. else:
  1961. return self.extra
  1962. def trim_start(self, names_with_path):
  1963. """
  1964. Trim joins from the start of the join path. The candidates for trim
  1965. are the PathInfos in names_with_path structure that are m2m joins.
  1966. Also set the select column so the start matches the join.
  1967. This method is meant to be used for generating the subquery joins &
  1968. cols in split_exclude().
  1969. Return a lookup usable for doing outerq.filter(lookup=self) and a
  1970. boolean indicating if the joins in the prefix contain a LEFT OUTER join.
  1971. _"""
  1972. all_paths = []
  1973. for _, paths in names_with_path:
  1974. all_paths.extend(paths)
  1975. contains_louter = False
  1976. # Trim and operate only on tables that were generated for
  1977. # the lookup part of the query. That is, avoid trimming
  1978. # joins generated for F() expressions.
  1979. lookup_tables = [
  1980. t for t in self.alias_map
  1981. if t in self._lookup_joins or t == self.base_table
  1982. ]
  1983. for trimmed_paths, path in enumerate(all_paths):
  1984. if path.m2m:
  1985. break
  1986. if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER:
  1987. contains_louter = True
  1988. alias = lookup_tables[trimmed_paths]
  1989. self.unref_alias(alias)
  1990. # The path.join_field is a Rel, lets get the other side's field
  1991. join_field = path.join_field.field
  1992. # Build the filter prefix.
  1993. paths_in_prefix = trimmed_paths
  1994. trimmed_prefix = []
  1995. for name, path in names_with_path:
  1996. if paths_in_prefix - len(path) < 0:
  1997. break
  1998. trimmed_prefix.append(name)
  1999. paths_in_prefix -= len(path)
  2000. trimmed_prefix.append(
  2001. join_field.foreign_related_fields[0].name)
  2002. trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
  2003. # Lets still see if we can trim the first join from the inner query
  2004. # (that is, self). We can't do this for:
  2005. # - LEFT JOINs because we would miss those rows that have nothing on
  2006. # the outer side,
  2007. # - INNER JOINs from filtered relations because we would miss their
  2008. # filters.
  2009. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]]
  2010. if first_join.join_type != LOUTER and not first_join.filtered_relation:
  2011. select_fields = [r[0] for r in join_field.related_fields]
  2012. select_alias = lookup_tables[trimmed_paths + 1]
  2013. self.unref_alias(lookup_tables[trimmed_paths])
  2014. extra_restriction = join_field.get_extra_restriction(
  2015. self.where_class, None, lookup_tables[trimmed_paths + 1])
  2016. if extra_restriction:
  2017. self.where.add(extra_restriction, AND)
  2018. else:
  2019. # TODO: It might be possible to trim more joins from the start of the
  2020. # inner query if it happens to have a longer join chain containing the
  2021. # values in select_fields. Lets punt this one for now.
  2022. select_fields = [r[1] for r in join_field.related_fields]
  2023. select_alias = lookup_tables[trimmed_paths]
  2024. # The found starting point is likely a Join instead of a BaseTable reference.
  2025. # But the first entry in the query's FROM clause must not be a JOIN.
  2026. for table in self.alias_map:
  2027. if self.alias_refcount[table] > 0:
  2028. self.alias_map[table] = BaseTable(self.alias_map[table].table_name, table)
  2029. break
  2030. self.set_select([f.get_col(select_alias) for f in select_fields])
  2031. return trimmed_prefix, contains_louter
  2032. def is_nullable(self, field):
  2033. """
  2034. Check if the given field should be treated as nullable.
  2035. Some backends treat '' as null and Django treats such fields as
  2036. nullable for those backends. In such situations field.null can be
  2037. False even if we should treat the field as nullable.
  2038. """
  2039. # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
  2040. # (nor should it have) knowledge of which connection is going to be
  2041. # used. The proper fix would be to defer all decisions where
  2042. # is_nullable() is needed to the compiler stage, but that is not easy
  2043. # to do currently.
  2044. return (
  2045. connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
  2046. field.empty_strings_allowed
  2047. ) or field.null
  2048. def get_order_dir(field, default='ASC'):
  2049. """
  2050. Return the field name and direction for an order specification. For
  2051. example, '-foo' is returned as ('foo', 'DESC').
  2052. The 'default' param is used to indicate which way no prefix (or a '+'
  2053. prefix) should sort. The '-' prefix always sorts the opposite way.
  2054. """
  2055. dirn = ORDER_DIR[default]
  2056. if field[0] == '-':
  2057. return field[1:], dirn[1]
  2058. return field, dirn[0]
  2059. def add_to_dict(data, key, value):
  2060. """
  2061. Add "value" to the set of values for "key", whether or not "key" already
  2062. exists.
  2063. """
  2064. if key in data:
  2065. data[key].add(value)
  2066. else:
  2067. data[key] = {value}
  2068. def is_reverse_o2o(field):
  2069. """
  2070. Check if the given field is reverse-o2o. The field is expected to be some
  2071. sort of relation field or related object.
  2072. """
  2073. return field.is_relation and field.one_to_one and not field.concrete
  2074. class JoinPromoter:
  2075. """
  2076. A class to abstract away join promotion problems for complex filter
  2077. conditions.
  2078. """
  2079. def __init__(self, connector, num_children, negated):
  2080. self.connector = connector
  2081. self.negated = negated
  2082. if self.negated:
  2083. if connector == AND:
  2084. self.effective_connector = OR
  2085. else:
  2086. self.effective_connector = AND
  2087. else:
  2088. self.effective_connector = self.connector
  2089. self.num_children = num_children
  2090. # Maps of table alias to how many times it is seen as required for
  2091. # inner and/or outer joins.
  2092. self.votes = Counter()
  2093. def add_votes(self, votes):
  2094. """
  2095. Add single vote per item to self.votes. Parameter can be any
  2096. iterable.
  2097. """
  2098. self.votes.update(votes)
  2099. def update_join_types(self, query):
  2100. """
  2101. Change join types so that the generated query is as efficient as
  2102. possible, but still correct. So, change as many joins as possible
  2103. to INNER, but don't make OUTER joins INNER if that could remove
  2104. results from the query.
  2105. """
  2106. to_promote = set()
  2107. to_demote = set()
  2108. # The effective_connector is used so that NOT (a AND b) is treated
  2109. # similarly to (a OR b) for join promotion.
  2110. for table, votes in self.votes.items():
  2111. # We must use outer joins in OR case when the join isn't contained
  2112. # in all of the joins. Otherwise the INNER JOIN itself could remove
  2113. # valid results. Consider the case where a model with rel_a and
  2114. # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
  2115. # if rel_a join doesn't produce any results is null (for example
  2116. # reverse foreign key or null value in direct foreign key), and
  2117. # there is a matching row in rel_b with col=2, then an INNER join
  2118. # to rel_a would remove a valid match from the query. So, we need
  2119. # to promote any existing INNER to LOUTER (it is possible this
  2120. # promotion in turn will be demoted later on).
  2121. if self.effective_connector == 'OR' and votes < self.num_children:
  2122. to_promote.add(table)
  2123. # If connector is AND and there is a filter that can match only
  2124. # when there is a joinable row, then use INNER. For example, in
  2125. # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
  2126. # as join output, then the col=1 or col=2 can't match (as
  2127. # NULL=anything is always false).
  2128. # For the OR case, if all children voted for a join to be inner,
  2129. # then we can use INNER for the join. For example:
  2130. # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
  2131. # then if rel_a doesn't produce any rows, the whole condition
  2132. # can't match. Hence we can safely use INNER join.
  2133. if self.effective_connector == 'AND' or (
  2134. self.effective_connector == 'OR' and votes == self.num_children):
  2135. to_demote.add(table)
  2136. # Finally, what happens in cases where we have:
  2137. # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
  2138. # Now, we first generate the OR clause, and promote joins for it
  2139. # in the first if branch above. Both rel_a and rel_b are promoted
  2140. # to LOUTER joins. After that we do the AND case. The OR case
  2141. # voted no inner joins but the rel_a__col__gte=0 votes inner join
  2142. # for rel_a. We demote it back to INNER join (in AND case a single
  2143. # vote is enough). The demotion is OK, if rel_a doesn't produce
  2144. # rows, then the rel_a__col__gte=0 clause can't be true, and thus
  2145. # the whole clause must be false. So, it is safe to use INNER
  2146. # join.
  2147. # Note that in this example we could just as well have the __gte
  2148. # clause and the OR clause swapped. Or we could replace the __gte
  2149. # clause with an OR clause containing rel_a__col=1|rel_a__col=2,
  2150. # and again we could safely demote to INNER.
  2151. query.promote_joins(to_promote)
  2152. query.demote_joins(to_demote)
  2153. return to_demote