query.py 107 KB

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