Development of an internal social media platform with personalised dashboards for students
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 97KB

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