You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.py 98KB

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