query.py 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  1. """
  2. The main QuerySet implementation. This provides the public API for the ORM.
  3. """
  4. import copy
  5. import operator
  6. import warnings
  7. from contextlib import nullcontext
  8. from functools import reduce
  9. from itertools import chain, islice
  10. from weakref import ref as weak_ref
  11. from asgiref.sync import sync_to_async
  12. import django
  13. from django.conf import settings
  14. from django.core import exceptions
  15. from django.db import (
  16. DJANGO_VERSION_PICKLE_KEY,
  17. IntegrityError,
  18. NotSupportedError,
  19. connections,
  20. router,
  21. transaction,
  22. )
  23. from django.db.models import AutoField, DateField, DateTimeField, Field, Max, sql
  24. from django.db.models.constants import LOOKUP_SEP, OnConflict
  25. from django.db.models.deletion import Collector
  26. from django.db.models.expressions import Case, DatabaseDefault, F, OrderBy, Value, When
  27. from django.db.models.fetch_modes import FETCH_ONE
  28. from django.db.models.functions import Cast, Trunc
  29. from django.db.models.query_utils import PROHIBITED_FILTER_KWARGS, FilteredRelation, Q
  30. from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE, ROW_COUNT
  31. from django.db.models.utils import (
  32. AltersData,
  33. create_namedtuple_class,
  34. resolve_callables,
  35. )
  36. from django.utils import timezone
  37. from django.utils.deprecation import RemovedInDjango70Warning, warn_about_external_use
  38. from django.utils.functional import cached_property
  39. # The maximum number of results to fetch in a get() query.
  40. MAX_GET_RESULTS = 21
  41. # The maximum number of items to display in a QuerySet.__repr__
  42. REPR_OUTPUT_SIZE = 20
  43. DEFAULT_FETCH_MODE = FETCH_ONE
  44. class BaseIterable:
  45. def __init__(
  46. self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE
  47. ):
  48. self.queryset = queryset
  49. self.chunked_fetch = chunked_fetch
  50. self.chunk_size = chunk_size
  51. async def _async_generator(self):
  52. # Generators don't actually start running until the first time you call
  53. # next() on them, so make the generator object in the async thread and
  54. # then repeatedly dispatch to it in a sync thread.
  55. sync_generator = self.__iter__()
  56. def next_slice(gen):
  57. return list(islice(gen, self.chunk_size))
  58. while True:
  59. chunk = await sync_to_async(next_slice)(sync_generator)
  60. for item in chunk:
  61. yield item
  62. if len(chunk) < self.chunk_size:
  63. break
  64. # __aiter__() is a *synchronous* method that has to then return an
  65. # *asynchronous* iterator/generator. Thus, nest an async generator inside
  66. # it.
  67. # This is a generic iterable converter for now, and is going to suffer a
  68. # performance penalty on large sets of items due to the cost of crossing
  69. # over the sync barrier for each chunk. Custom __aiter__() methods should
  70. # be added to each Iterable subclass, but that needs some work in the
  71. # Compiler first.
  72. def __aiter__(self):
  73. return self._async_generator()
  74. class ModelIterable(BaseIterable):
  75. """Iterable that yields a model instance for each row."""
  76. def __iter__(self):
  77. queryset = self.queryset
  78. db = queryset.db
  79. compiler = queryset.query.get_compiler(using=db)
  80. fetch_mode = queryset._fetch_mode
  81. # Execute the query. This will also fill compiler.select, klass_info,
  82. # and annotations.
  83. results = compiler.execute_sql(
  84. chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
  85. )
  86. select, klass_info, annotation_col_map = (
  87. compiler.select,
  88. compiler.klass_info,
  89. compiler.annotation_col_map,
  90. )
  91. model_cls = klass_info["model"]
  92. select_fields = klass_info["select_fields"]
  93. model_fields_start, model_fields_end = select_fields[0], select_fields[-1] + 1
  94. init_list = [
  95. f[0].target.attname for f in select[model_fields_start:model_fields_end]
  96. ]
  97. related_populators = get_related_populators(klass_info, select, db, fetch_mode)
  98. known_related_objects = [
  99. (
  100. field,
  101. related_objs,
  102. attnames := [
  103. (
  104. field.attname
  105. if from_field == "self"
  106. else queryset.model._meta.get_field(from_field).attname
  107. )
  108. for from_field in field.from_fields
  109. ],
  110. operator.attrgetter(*attnames),
  111. )
  112. for field, related_objs in queryset._known_related_objects.items()
  113. ]
  114. peers = []
  115. for row in compiler.results_iter(results):
  116. obj = model_cls.from_db(
  117. db,
  118. init_list,
  119. row[model_fields_start:model_fields_end],
  120. fetch_mode=fetch_mode,
  121. )
  122. if fetch_mode.track_peers:
  123. peers.append(weak_ref(obj))
  124. obj._state.peers = peers
  125. for rel_populator in related_populators:
  126. rel_populator.populate(row, obj)
  127. if annotation_col_map:
  128. for attr_name, col_pos in annotation_col_map.items():
  129. setattr(obj, attr_name, row[col_pos])
  130. # Add the known related objects to the model.
  131. for field, rel_objs, rel_attnames, rel_getter in known_related_objects:
  132. # Avoid overwriting objects loaded by, e.g., select_related().
  133. if field.is_cached(obj):
  134. continue
  135. # Avoid fetching potentially deferred attributes that would
  136. # result in unexpected queries.
  137. if any(attname not in obj.__dict__ for attname in rel_attnames):
  138. continue
  139. rel_obj_id = rel_getter(obj)
  140. try:
  141. rel_obj = rel_objs[rel_obj_id]
  142. except KeyError:
  143. pass # May happen in qs1 | qs2 scenarios.
  144. else:
  145. setattr(obj, field.name, rel_obj)
  146. yield obj
  147. class RawModelIterable(BaseIterable):
  148. """
  149. Iterable that yields a model instance for each row from a raw queryset.
  150. """
  151. def __iter__(self):
  152. # Cache some things for performance reasons outside the loop.
  153. db = self.queryset.db
  154. query = self.queryset.query
  155. connection = connections[db]
  156. compiler = connection.ops.compiler("SQLCompiler")(query, connection, db)
  157. query_iterator = iter(query)
  158. try:
  159. (
  160. model_init_names,
  161. model_init_pos,
  162. annotation_fields,
  163. ) = self.queryset.resolve_model_init_order()
  164. model_cls = self.queryset.model
  165. if any(
  166. f.attname not in model_init_names for f in model_cls._meta.pk_fields
  167. ):
  168. raise exceptions.FieldDoesNotExist(
  169. "Raw query must include the primary key"
  170. )
  171. fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns]
  172. cols = [f.get_col(f.model._meta.db_table) if f else None for f in fields]
  173. converters = compiler.get_converters(cols)
  174. if converters:
  175. query_iterator = compiler.apply_converters(query_iterator, converters)
  176. if compiler.has_composite_fields(cols):
  177. query_iterator = compiler.composite_fields_to_tuples(
  178. query_iterator, cols
  179. )
  180. fetch_mode = self.queryset._fetch_mode
  181. peers = []
  182. for values in query_iterator:
  183. # Associate fields to values
  184. model_init_values = [values[pos] for pos in model_init_pos]
  185. instance = model_cls.from_db(
  186. db, model_init_names, model_init_values, fetch_mode=fetch_mode
  187. )
  188. if fetch_mode.track_peers:
  189. peers.append(weak_ref(instance))
  190. instance._state.peers = peers
  191. if annotation_fields:
  192. for column, pos in annotation_fields:
  193. setattr(instance, column, values[pos])
  194. yield instance
  195. finally:
  196. # Done iterating the Query. If it has its own cursor, close it.
  197. if hasattr(query, "cursor") and query.cursor:
  198. query.cursor.close()
  199. class ValuesIterable(BaseIterable):
  200. """
  201. Iterable returned by QuerySet.values() that yields a dict for each row.
  202. """
  203. def __iter__(self):
  204. queryset = self.queryset
  205. query = queryset.query
  206. compiler = query.get_compiler(queryset.db)
  207. if query.selected:
  208. names = list(query.selected)
  209. else:
  210. # extra(select=...) cols are always at the start of the row.
  211. names = [
  212. *query.extra_select,
  213. *query.values_select,
  214. *query.annotation_select,
  215. ]
  216. indexes = range(len(names))
  217. for row in compiler.results_iter(
  218. chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
  219. ):
  220. yield {names[i]: row[i] for i in indexes}
  221. class ValuesListIterable(BaseIterable):
  222. """
  223. Iterable returned by QuerySet.values_list(flat=False) that yields a tuple
  224. for each row.
  225. """
  226. def __iter__(self):
  227. queryset = self.queryset
  228. query = queryset.query
  229. compiler = query.get_compiler(queryset.db)
  230. return compiler.results_iter(
  231. tuple_expected=True,
  232. chunked_fetch=self.chunked_fetch,
  233. chunk_size=self.chunk_size,
  234. )
  235. class NamedValuesListIterable(ValuesListIterable):
  236. """
  237. Iterable returned by QuerySet.values_list(named=True) that yields a
  238. namedtuple for each row.
  239. """
  240. def __iter__(self):
  241. queryset = self.queryset
  242. if queryset._fields:
  243. names = queryset._fields
  244. else:
  245. query = queryset.query
  246. names = [
  247. *query.extra_select,
  248. *query.values_select,
  249. *query.annotation_select,
  250. ]
  251. tuple_class = create_namedtuple_class(*names)
  252. new = tuple.__new__
  253. for row in super().__iter__():
  254. yield new(tuple_class, row)
  255. class FlatValuesListIterable(BaseIterable):
  256. """
  257. Iterable returned by QuerySet.values_list(flat=True) that yields single
  258. values.
  259. """
  260. def __iter__(self):
  261. queryset = self.queryset
  262. compiler = queryset.query.get_compiler(queryset.db)
  263. for row in compiler.results_iter(
  264. chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
  265. ):
  266. yield row[0]
  267. class PreventQuerySetCloning:
  268. """
  269. Temporarily prevent the given QuerySet from creating new QuerySet instances
  270. on each mutating operation (e.g: filter(), exclude() etc), instead
  271. modifying the QuerySet in-place.
  272. @contextlib.contextmanager is intentionally not used for performance
  273. reasons.
  274. """
  275. __slots__ = ("queryset",)
  276. def __init__(self, queryset):
  277. self.queryset = queryset
  278. def __enter__(self):
  279. return self.queryset._disable_cloning()
  280. def __exit__(self, exc_type, exc_value, traceback):
  281. self.queryset._enable_cloning()
  282. class QuerySet(AltersData):
  283. """Represent a lazy database lookup for a set of objects."""
  284. def __init__(self, model=None, query=None, using=None, hints=None):
  285. self.model = model
  286. self._db = using
  287. self._hints = hints or {}
  288. self._query = query or sql.Query(self.model)
  289. self._result_cache = None
  290. self._sticky_filter = False
  291. self._for_write = False
  292. self._prefetch_related_lookups = ()
  293. self._prefetch_done = False
  294. self._known_related_objects = {} # {rel_field: {pk: rel_obj}}
  295. self._iterable_class = ModelIterable
  296. self._fetch_mode = DEFAULT_FETCH_MODE
  297. self._fields = None
  298. self._defer_next_filter = False
  299. self._deferred_filter = None
  300. self._cloning_enabled = True
  301. @property
  302. def query(self):
  303. if self._deferred_filter:
  304. negate, args, kwargs = self._deferred_filter
  305. self._filter_or_exclude_inplace(negate, args, kwargs)
  306. self._deferred_filter = None
  307. return self._query
  308. @query.setter
  309. def query(self, value):
  310. if value.values_select:
  311. self._iterable_class = ValuesIterable
  312. self._query = value
  313. def as_manager(cls):
  314. # Address the circular dependency between `Queryset` and `Manager`.
  315. from django.db.models.manager import Manager
  316. manager = Manager.from_queryset(cls)()
  317. manager._built_with_as_manager = True
  318. return manager
  319. as_manager.queryset_only = True
  320. as_manager = classmethod(as_manager)
  321. ########################
  322. # PYTHON MAGIC METHODS #
  323. ########################
  324. def __deepcopy__(self, memo):
  325. """Don't populate the QuerySet's cache."""
  326. obj = self.__class__()
  327. for k, v in self.__dict__.items():
  328. if k == "_result_cache":
  329. obj.__dict__[k] = None
  330. else:
  331. obj.__dict__[k] = copy.deepcopy(v, memo)
  332. return obj
  333. def __getstate__(self):
  334. # Force the cache to be fully populated.
  335. self._fetch_all()
  336. return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}
  337. def __setstate__(self, state):
  338. pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
  339. if pickled_version:
  340. if pickled_version != django.__version__:
  341. warnings.warn(
  342. "Pickled queryset instance's Django version %s does not "
  343. "match the current version %s."
  344. % (pickled_version, django.__version__),
  345. RuntimeWarning,
  346. stacklevel=2,
  347. )
  348. else:
  349. warnings.warn(
  350. "Pickled queryset instance's Django version is not specified.",
  351. RuntimeWarning,
  352. stacklevel=2,
  353. )
  354. self.__dict__.update(state)
  355. def __repr__(self):
  356. data = list(self[: REPR_OUTPUT_SIZE + 1])
  357. if len(data) > REPR_OUTPUT_SIZE:
  358. data[-1] = "...(remaining elements truncated)..."
  359. return "<%s %r>" % (self.__class__.__name__, data)
  360. def __len__(self):
  361. self._fetch_all()
  362. return len(self._result_cache)
  363. def __iter__(self):
  364. """
  365. The queryset iterator protocol uses three nested iterators in the
  366. default case:
  367. 1. sql.compiler.execute_sql()
  368. - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)
  369. using cursor.fetchmany(). This part is responsible for
  370. doing some column masking, and returning the rows in chunks.
  371. 2. sql.compiler.results_iter()
  372. - Returns one row at time. At this point the rows are still just
  373. tuples. In some cases the return values are converted to
  374. Python values at this location.
  375. 3. self.iterator()
  376. - Responsible for turning the rows into model objects.
  377. """
  378. self._fetch_all()
  379. return iter(self._result_cache)
  380. def __aiter__(self):
  381. # Remember, __aiter__ itself is synchronous, it's the thing it returns
  382. # that is async!
  383. async def generator():
  384. await sync_to_async(self._fetch_all)()
  385. for item in self._result_cache:
  386. yield item
  387. return generator()
  388. def __bool__(self):
  389. self._fetch_all()
  390. return bool(self._result_cache)
  391. def __getitem__(self, k):
  392. """Retrieve an item or slice from the set of results."""
  393. if not isinstance(k, (int, slice)):
  394. raise TypeError(
  395. "QuerySet indices must be integers or slices, not %s."
  396. % type(k).__name__
  397. )
  398. if (isinstance(k, int) and k < 0) or (
  399. isinstance(k, slice)
  400. and (
  401. (k.start is not None and k.start < 0)
  402. or (k.stop is not None and k.stop < 0)
  403. )
  404. ):
  405. raise ValueError("Negative indexing is not supported.")
  406. if self._result_cache is not None:
  407. return self._result_cache[k]
  408. if isinstance(k, slice):
  409. qs = self._chain()
  410. if k.start is not None:
  411. start = int(k.start)
  412. else:
  413. start = None
  414. if k.stop is not None:
  415. stop = int(k.stop)
  416. else:
  417. stop = None
  418. qs.query.set_limits(start, stop)
  419. return list(qs)[:: k.step] if k.step else qs
  420. qs = self._chain()
  421. qs.query.set_limits(k, k + 1)
  422. qs._fetch_all()
  423. return qs._result_cache[0]
  424. def __class_getitem__(cls, *args, **kwargs):
  425. return cls
  426. def __and__(self, other):
  427. self._check_operator_queryset(other, "&")
  428. self._merge_sanity_check(other)
  429. if isinstance(other, EmptyQuerySet):
  430. return other
  431. if isinstance(self, EmptyQuerySet):
  432. return self
  433. combined = self._chain()
  434. combined._merge_known_related_objects(other)
  435. combined.query.combine(other.query, sql.AND)
  436. return combined
  437. def __or__(self, other):
  438. self._check_operator_queryset(other, "|")
  439. self._merge_sanity_check(other)
  440. if isinstance(self, EmptyQuerySet):
  441. return other
  442. if isinstance(other, EmptyQuerySet):
  443. return self
  444. query = (
  445. self
  446. if self.query.can_filter()
  447. else self.model._base_manager.filter(pk__in=self.values("pk"))
  448. )
  449. combined = query._chain()
  450. combined._merge_known_related_objects(other)
  451. if not other.query.can_filter():
  452. other = other.model._base_manager.filter(pk__in=other.values("pk"))
  453. combined.query.combine(other.query, sql.OR)
  454. return combined
  455. def __xor__(self, other):
  456. self._check_operator_queryset(other, "^")
  457. self._merge_sanity_check(other)
  458. if isinstance(self, EmptyQuerySet):
  459. return other
  460. if isinstance(other, EmptyQuerySet):
  461. return self
  462. query = (
  463. self
  464. if self.query.can_filter()
  465. else self.model._base_manager.filter(pk__in=self.values("pk"))
  466. )
  467. combined = query._chain()
  468. combined._merge_known_related_objects(other)
  469. if not other.query.can_filter():
  470. other = other.model._base_manager.filter(pk__in=other.values("pk"))
  471. combined.query.combine(other.query, sql.XOR)
  472. return combined
  473. ####################################
  474. # METHODS THAT DO DATABASE QUERIES #
  475. ####################################
  476. def _iterator(self, use_chunked_fetch, chunk_size):
  477. iterable = self._iterable_class(
  478. self,
  479. chunked_fetch=use_chunked_fetch,
  480. chunk_size=chunk_size or 2000,
  481. )
  482. if not self._prefetch_related_lookups or chunk_size is None:
  483. yield from iterable
  484. return
  485. iterator = iter(iterable)
  486. while results := list(islice(iterator, chunk_size)):
  487. prefetch_related_objects(results, *self._prefetch_related_lookups)
  488. yield from results
  489. def iterator(self, chunk_size=None):
  490. """
  491. An iterator over the results from applying this QuerySet to the
  492. database. chunk_size must be provided for QuerySets that prefetch
  493. related objects. Otherwise, a default chunk_size of 2000 is supplied.
  494. """
  495. if chunk_size is None:
  496. if self._prefetch_related_lookups:
  497. raise ValueError(
  498. "chunk_size must be provided when using QuerySet.iterator() after "
  499. "prefetch_related()."
  500. )
  501. elif chunk_size <= 0:
  502. raise ValueError("Chunk size must be strictly positive.")
  503. use_chunked_fetch = not connections[self.db].settings_dict.get(
  504. "DISABLE_SERVER_SIDE_CURSORS"
  505. )
  506. return self._iterator(use_chunked_fetch, chunk_size)
  507. async def aiterator(self, chunk_size=2000):
  508. """
  509. An asynchronous iterator over the results from applying this QuerySet
  510. to the database.
  511. """
  512. if chunk_size <= 0:
  513. raise ValueError("Chunk size must be strictly positive.")
  514. use_chunked_fetch = not connections[self.db].settings_dict.get(
  515. "DISABLE_SERVER_SIDE_CURSORS"
  516. )
  517. iterable = self._iterable_class(
  518. self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size
  519. )
  520. if self._prefetch_related_lookups:
  521. results = []
  522. async for item in iterable:
  523. results.append(item)
  524. if len(results) >= chunk_size:
  525. await aprefetch_related_objects(
  526. results, *self._prefetch_related_lookups
  527. )
  528. for result in results:
  529. yield result
  530. results.clear()
  531. if results:
  532. await aprefetch_related_objects(
  533. results, *self._prefetch_related_lookups
  534. )
  535. for result in results:
  536. yield result
  537. else:
  538. async for item in iterable:
  539. yield item
  540. def aggregate(self, *args, **kwargs):
  541. """
  542. Return a dictionary containing the calculations (aggregation)
  543. over the current queryset.
  544. If args is present the expression is passed as a kwarg using
  545. the Aggregate object's default alias.
  546. """
  547. if self.query.distinct_fields:
  548. raise NotImplementedError("aggregate() + distinct(fields) not implemented.")
  549. self._validate_values_are_expressions(
  550. (*args, *kwargs.values()), method_name="aggregate"
  551. )
  552. for arg in args:
  553. # The default_alias property raises TypeError if default_alias
  554. # can't be set automatically or AttributeError if it isn't an
  555. # attribute.
  556. try:
  557. arg.default_alias
  558. except (AttributeError, TypeError):
  559. raise TypeError("Complex aggregates require an alias")
  560. kwargs[arg.default_alias] = arg
  561. return self.query.chain().get_aggregation(self.db, kwargs)
  562. async def aaggregate(self, *args, **kwargs):
  563. return await sync_to_async(self.aggregate)(*args, **kwargs)
  564. def count(self):
  565. """
  566. Perform a SELECT COUNT() and return the number of records as an
  567. integer.
  568. If the QuerySet is already fully cached, return the length of the
  569. cached results set to avoid multiple SELECT COUNT(*) calls.
  570. """
  571. if self._result_cache is not None:
  572. return len(self._result_cache)
  573. return self.query.get_count(using=self.db)
  574. async def acount(self):
  575. return await sync_to_async(self.count)()
  576. def get(self, *args, **kwargs):
  577. """
  578. Perform the query and return a single object matching the given
  579. keyword arguments.
  580. """
  581. if self.query.combinator and (args or kwargs):
  582. raise NotSupportedError(
  583. "Calling QuerySet.get(...) with filters after %s() is not "
  584. "supported." % self.query.combinator
  585. )
  586. clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  587. if self.query.can_filter() and not self.query.distinct_fields:
  588. clone = clone.order_by()
  589. limit = None
  590. if (
  591. not clone.query.select_for_update
  592. or connections[clone.db].features.supports_select_for_update_with_limit
  593. ):
  594. limit = MAX_GET_RESULTS
  595. clone.query.set_limits(high=limit)
  596. num = len(clone)
  597. if num == 1:
  598. return clone._result_cache[0]
  599. if not num:
  600. raise self.model.DoesNotExist(
  601. "%s matching query does not exist." % self.model._meta.object_name
  602. )
  603. raise self.model.MultipleObjectsReturned(
  604. "get() returned more than one %s -- it returned %s!"
  605. % (
  606. self.model._meta.object_name,
  607. num if not limit or num < limit else "more than %s" % (limit - 1),
  608. )
  609. )
  610. async def aget(self, *args, **kwargs):
  611. return await sync_to_async(self.get)(*args, **kwargs)
  612. def create(self, **kwargs):
  613. """
  614. Create a new object with the given kwargs, saving it to the database
  615. and returning the created object.
  616. """
  617. reverse_one_to_one_fields = frozenset(kwargs).intersection(
  618. self.model._meta._reverse_one_to_one_field_names
  619. )
  620. if reverse_one_to_one_fields:
  621. raise ValueError(
  622. "The following fields do not exist in this model: %s"
  623. % ", ".join(reverse_one_to_one_fields)
  624. )
  625. obj = self.model(**kwargs)
  626. self._for_write = True
  627. obj.save(force_insert=True, using=self.db)
  628. obj._state.fetch_mode = self._fetch_mode
  629. return obj
  630. create.alters_data = True
  631. async def acreate(self, **kwargs):
  632. return await sync_to_async(self.create)(**kwargs)
  633. acreate.alters_data = True
  634. def _prepare_for_bulk_create(self, objs):
  635. objs_with_pk, objs_without_pk = [], []
  636. for obj in objs:
  637. obj._prepare_related_fields_for_save(operation_name="bulk_create")
  638. if isinstance(obj.pk, DatabaseDefault):
  639. objs_without_pk.append(obj)
  640. elif obj._is_pk_set():
  641. objs_with_pk.append(obj)
  642. else:
  643. obj.pk = obj._meta.pk.get_pk_value_on_save(obj)
  644. if obj._is_pk_set():
  645. objs_with_pk.append(obj)
  646. else:
  647. objs_without_pk.append(obj)
  648. return objs_with_pk, objs_without_pk
  649. def _check_bulk_create_options(
  650. self, ignore_conflicts, update_conflicts, update_fields, unique_fields
  651. ):
  652. if ignore_conflicts and update_conflicts:
  653. raise ValueError(
  654. "ignore_conflicts and update_conflicts are mutually exclusive."
  655. )
  656. db_features = connections[self.db].features
  657. if ignore_conflicts:
  658. if not db_features.supports_ignore_conflicts:
  659. raise NotSupportedError(
  660. "This database backend does not support ignoring conflicts."
  661. )
  662. return OnConflict.IGNORE
  663. elif update_conflicts:
  664. if not db_features.supports_update_conflicts:
  665. raise NotSupportedError(
  666. "This database backend does not support updating conflicts."
  667. )
  668. if not update_fields:
  669. raise ValueError(
  670. "Fields that will be updated when a row insertion fails "
  671. "on conflicts must be provided."
  672. )
  673. if unique_fields and not db_features.supports_update_conflicts_with_target:
  674. raise NotSupportedError(
  675. "This database backend does not support updating "
  676. "conflicts with specifying unique fields that can trigger "
  677. "the upsert."
  678. )
  679. if not unique_fields and db_features.supports_update_conflicts_with_target:
  680. raise ValueError(
  681. "Unique fields that can trigger the upsert must be provided."
  682. )
  683. # Updating primary keys and non-concrete fields is forbidden.
  684. if any(not f.concrete for f in update_fields):
  685. raise ValueError(
  686. "bulk_create() can only be used with concrete fields in "
  687. "update_fields."
  688. )
  689. if any(f in self.model._meta.pk_fields for f in update_fields):
  690. raise ValueError(
  691. "bulk_create() cannot be used with primary keys in "
  692. "update_fields."
  693. )
  694. if unique_fields:
  695. if any(not f.concrete for f in unique_fields):
  696. raise ValueError(
  697. "bulk_create() can only be used with concrete fields "
  698. "in unique_fields."
  699. )
  700. return OnConflict.UPDATE
  701. return None
  702. def bulk_create(
  703. self,
  704. objs,
  705. batch_size=None,
  706. ignore_conflicts=False,
  707. update_conflicts=False,
  708. update_fields=None,
  709. unique_fields=None,
  710. ):
  711. """
  712. Insert each of the instances into the database. Do *not* call
  713. save() on each of the instances, do not send any pre/post_save
  714. signals, and do not set the primary key attribute if it is an
  715. autoincrement field (except if
  716. features.can_return_rows_from_bulk_insert=True).
  717. Multi-table models are not supported.
  718. """
  719. # When you bulk insert you don't get the primary keys back (if it's an
  720. # autoincrement, except if can_return_rows_from_bulk_insert=True), so
  721. # you can't insert into the child tables which references this. There
  722. # are two workarounds:
  723. # 1) This could be implemented if you didn't have an autoincrement pk
  724. # 2) You could do it by doing O(n) normal inserts into the parent
  725. # tables to get the primary keys back and then doing a single bulk
  726. # insert into the childmost table.
  727. # We currently set the primary keys on the objects when using
  728. # PostgreSQL via the RETURNING ID clause. It should be possible for
  729. # Oracle as well, but the semantics for extracting the primary keys is
  730. # trickier so it's not done yet.
  731. if batch_size is not None and batch_size <= 0:
  732. raise ValueError("Batch size must be a positive integer.")
  733. # Check that the parents share the same concrete model with the our
  734. # model to detect the inheritance pattern ConcreteGrandParent ->
  735. # MultiTableParent -> ProxyChild. Simply checking
  736. # self.model._meta.proxy would not identify that case as involving
  737. # multiple tables.
  738. for parent in self.model._meta.all_parents:
  739. if parent._meta.concrete_model is not self.model._meta.concrete_model:
  740. raise ValueError("Can't bulk create a multi-table inherited model")
  741. if not objs:
  742. return objs
  743. opts = self.model._meta
  744. if unique_fields:
  745. # Primary key is allowed in unique_fields.
  746. unique_fields = [
  747. self.model._meta.get_field(opts.pk.name if name == "pk" else name)
  748. for name in unique_fields
  749. ]
  750. if update_fields:
  751. update_fields = [self.model._meta.get_field(name) for name in update_fields]
  752. on_conflict = self._check_bulk_create_options(
  753. ignore_conflicts,
  754. update_conflicts,
  755. update_fields,
  756. unique_fields,
  757. )
  758. self._for_write = True
  759. fields = [f for f in opts.concrete_fields if not f.generated]
  760. objs = list(objs)
  761. objs_with_pk, objs_without_pk = self._prepare_for_bulk_create(objs)
  762. if objs_with_pk and objs_without_pk:
  763. context = transaction.atomic(using=self.db, savepoint=False)
  764. else:
  765. context = nullcontext()
  766. with context:
  767. self._handle_order_with_respect_to(objs)
  768. if objs_with_pk:
  769. returned_columns = self._batched_insert(
  770. objs_with_pk,
  771. fields,
  772. batch_size,
  773. on_conflict=on_conflict,
  774. update_fields=update_fields,
  775. unique_fields=unique_fields,
  776. )
  777. for obj_with_pk, results in zip(objs_with_pk, returned_columns):
  778. for result, field in zip(results, opts.db_returning_fields):
  779. setattr(obj_with_pk, field.attname, result)
  780. for obj_with_pk in objs_with_pk:
  781. obj_with_pk._state.adding = False
  782. obj_with_pk._state.db = self.db
  783. if objs_without_pk:
  784. fields = [f for f in fields if not isinstance(f, AutoField)]
  785. returned_columns = self._batched_insert(
  786. objs_without_pk,
  787. fields,
  788. batch_size,
  789. on_conflict=on_conflict,
  790. update_fields=update_fields,
  791. unique_fields=unique_fields,
  792. )
  793. connection = connections[self.db]
  794. if (
  795. connection.features.can_return_rows_from_bulk_insert
  796. and on_conflict is None
  797. ):
  798. assert len(returned_columns) == len(objs_without_pk)
  799. for obj_without_pk, results in zip(objs_without_pk, returned_columns):
  800. for result, field in zip(results, opts.db_returning_fields):
  801. setattr(obj_without_pk, field.attname, result)
  802. obj_without_pk._state.adding = False
  803. obj_without_pk._state.db = self.db
  804. return objs
  805. def _handle_order_with_respect_to(self, objs):
  806. if objs and (order_wrt := self.model._meta.order_with_respect_to):
  807. get_filter_kwargs_for_object = order_wrt.get_filter_kwargs_for_object
  808. attnames = list(get_filter_kwargs_for_object(objs[0]))
  809. group_keys = set()
  810. obj_groups = []
  811. for obj in objs:
  812. group_key = tuple(get_filter_kwargs_for_object(obj).values())
  813. group_keys.add(group_key)
  814. obj_groups.append((obj, group_key))
  815. filters = [
  816. Q.create(list(zip(attnames, group_key))) for group_key in group_keys
  817. ]
  818. next_orders = (
  819. self.model._base_manager.using(self.db)
  820. .filter(reduce(operator.or_, filters))
  821. .values_list(*attnames)
  822. .annotate(_order__max=Max("_order") + 1)
  823. )
  824. # Create mapping of group values to max order.
  825. group_next_orders = dict.fromkeys(group_keys, 0)
  826. group_next_orders.update(
  827. (tuple(group_key), next_order) for *group_key, next_order in next_orders
  828. )
  829. # Assign _order values to new objects.
  830. for obj, group_key in obj_groups:
  831. if getattr(obj, "_order", None) is None:
  832. group_next_order = group_next_orders[group_key]
  833. obj._order = group_next_order
  834. group_next_orders[group_key] += 1
  835. bulk_create.alters_data = True
  836. async def abulk_create(
  837. self,
  838. objs,
  839. batch_size=None,
  840. ignore_conflicts=False,
  841. update_conflicts=False,
  842. update_fields=None,
  843. unique_fields=None,
  844. ):
  845. return await sync_to_async(self.bulk_create)(
  846. objs=objs,
  847. batch_size=batch_size,
  848. ignore_conflicts=ignore_conflicts,
  849. update_conflicts=update_conflicts,
  850. update_fields=update_fields,
  851. unique_fields=unique_fields,
  852. )
  853. abulk_create.alters_data = True
  854. def bulk_update(self, objs, fields, batch_size=None):
  855. """
  856. Update the given fields in each of the given objects in the database.
  857. """
  858. if batch_size is not None and batch_size <= 0:
  859. raise ValueError("Batch size must be a positive integer.")
  860. if not fields:
  861. raise ValueError("Field names must be given to bulk_update().")
  862. objs = tuple(objs)
  863. if not all(obj._is_pk_set() for obj in objs):
  864. raise ValueError("All bulk_update() objects must have a primary key set.")
  865. opts = self.model._meta
  866. fields = [opts.get_field(name) for name in fields]
  867. if any(not f.concrete for f in fields):
  868. raise ValueError("bulk_update() can only be used with concrete fields.")
  869. all_pk_fields = set(opts.pk_fields)
  870. for parent in opts.all_parents:
  871. all_pk_fields.update(parent._meta.pk_fields)
  872. if any(f in all_pk_fields for f in fields):
  873. raise ValueError("bulk_update() cannot be used with primary key fields.")
  874. if not objs:
  875. return 0
  876. for obj in objs:
  877. obj._prepare_related_fields_for_save(
  878. operation_name="bulk_update", fields=fields
  879. )
  880. # PK is used twice in the resulting update query, once in the filter
  881. # and once in the WHEN. Each field will also have one CAST.
  882. self._for_write = True
  883. connection = connections[self.db]
  884. max_batch_size = connection.ops.bulk_batch_size(
  885. [opts.pk, opts.pk, *fields], objs
  886. )
  887. batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size
  888. requires_casting = connection.features.requires_casted_case_in_updates
  889. batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size))
  890. updates = []
  891. for batch_objs in batches:
  892. update_kwargs = {}
  893. for field in fields:
  894. when_statements = []
  895. for obj in batch_objs:
  896. attr = getattr(obj, field.attname)
  897. if not hasattr(attr, "resolve_expression"):
  898. attr = Value(attr, output_field=field)
  899. when_statements.append(When(pk=obj.pk, then=attr))
  900. case_statement = Case(*when_statements, output_field=field)
  901. if requires_casting:
  902. case_statement = Cast(case_statement, output_field=field)
  903. update_kwargs[field.attname] = case_statement
  904. updates.append(([obj.pk for obj in batch_objs], update_kwargs))
  905. rows_updated = 0
  906. queryset = self.using(self.db)
  907. with transaction.atomic(using=self.db, savepoint=False):
  908. for pks, update_kwargs in updates:
  909. rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs)
  910. return rows_updated
  911. bulk_update.alters_data = True
  912. async def abulk_update(self, objs, fields, batch_size=None):
  913. return await sync_to_async(self.bulk_update)(
  914. objs=objs,
  915. fields=fields,
  916. batch_size=batch_size,
  917. )
  918. abulk_update.alters_data = True
  919. def get_or_create(self, defaults=None, **kwargs):
  920. """
  921. Look up an object with the given kwargs, creating one if necessary.
  922. Return a tuple of (object, created), where created is a boolean
  923. specifying whether an object was created.
  924. """
  925. # The get() needs to be targeted at the write database in order
  926. # to avoid potential transaction consistency problems.
  927. self._for_write = True
  928. try:
  929. return self.get(**kwargs), False
  930. except self.model.DoesNotExist:
  931. params = self._extract_model_params(defaults, **kwargs)
  932. # Try to create an object using passed params.
  933. try:
  934. with transaction.atomic(using=self.db):
  935. params = dict(resolve_callables(params))
  936. return self.create(**params), True
  937. except IntegrityError:
  938. try:
  939. return self.get(**kwargs), False
  940. except self.model.DoesNotExist:
  941. pass
  942. raise
  943. get_or_create.alters_data = True
  944. async def aget_or_create(self, defaults=None, **kwargs):
  945. return await sync_to_async(self.get_or_create)(
  946. defaults=defaults,
  947. **kwargs,
  948. )
  949. aget_or_create.alters_data = True
  950. def update_or_create(self, defaults=None, create_defaults=None, **kwargs):
  951. """
  952. Look up an object with the given kwargs, updating one with defaults
  953. if it exists, otherwise create a new one. Optionally, an object can
  954. be created with different values than defaults by using
  955. create_defaults.
  956. Return a tuple (object, created), where created is a boolean
  957. specifying whether an object was created.
  958. """
  959. update_defaults = defaults or {}
  960. if create_defaults is None:
  961. create_defaults = update_defaults
  962. self._for_write = True
  963. with transaction.atomic(using=self.db):
  964. # Lock the row so that a concurrent update is blocked until
  965. # update_or_create() has performed its save.
  966. obj, created = self.select_for_update().get_or_create(
  967. create_defaults, **kwargs
  968. )
  969. if created:
  970. return obj, created
  971. for k, v in resolve_callables(update_defaults):
  972. setattr(obj, k, v)
  973. update_fields = set(update_defaults)
  974. concrete_field_names = self.model._meta._non_pk_concrete_field_names
  975. # update_fields does not support non-concrete fields.
  976. if concrete_field_names.issuperset(update_fields):
  977. # Add fields which are set on pre_save(), e.g. auto_now fields.
  978. # This is to maintain backward compatibility as these fields
  979. # are not updated unless explicitly specified in the
  980. # update_fields list.
  981. pk_fields = self.model._meta.pk_fields
  982. for field in self.model._meta.local_concrete_fields:
  983. if not (
  984. field in pk_fields or field.__class__.pre_save is Field.pre_save
  985. ):
  986. update_fields.add(field.name)
  987. if field.name != field.attname:
  988. update_fields.add(field.attname)
  989. obj.save(using=self.db, update_fields=update_fields)
  990. else:
  991. obj.save(using=self.db)
  992. return obj, False
  993. update_or_create.alters_data = True
  994. async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs):
  995. return await sync_to_async(self.update_or_create)(
  996. defaults=defaults,
  997. create_defaults=create_defaults,
  998. **kwargs,
  999. )
  1000. aupdate_or_create.alters_data = True
  1001. def _extract_model_params(self, defaults, **kwargs):
  1002. """
  1003. Prepare `params` for creating a model instance based on the given
  1004. kwargs; for use by get_or_create().
  1005. """
  1006. defaults = defaults or {}
  1007. params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}
  1008. params.update(defaults)
  1009. property_names = self.model._meta._property_names
  1010. invalid_params = []
  1011. for param in params:
  1012. try:
  1013. self.model._meta.get_field(param)
  1014. except exceptions.FieldDoesNotExist:
  1015. # It's okay to use a model's property if it has a setter.
  1016. if not (param in property_names and getattr(self.model, param).fset):
  1017. invalid_params.append(param)
  1018. if invalid_params:
  1019. raise exceptions.FieldError(
  1020. "Invalid field name(s) for model %s: '%s'."
  1021. % (
  1022. self.model._meta.object_name,
  1023. "', '".join(sorted(invalid_params)),
  1024. )
  1025. )
  1026. return params
  1027. def _earliest(self, *fields):
  1028. """
  1029. Return the earliest object according to fields (if given) or by the
  1030. model's Meta.get_latest_by.
  1031. """
  1032. if fields:
  1033. order_by = fields
  1034. else:
  1035. order_by = getattr(self.model._meta, "get_latest_by")
  1036. if order_by and not isinstance(order_by, (tuple, list)):
  1037. order_by = (order_by,)
  1038. if order_by is None:
  1039. raise ValueError(
  1040. "earliest() and latest() require either fields as positional "
  1041. "arguments or 'get_latest_by' in the model's Meta."
  1042. )
  1043. obj = self._chain()
  1044. obj.query.set_limits(high=1)
  1045. obj.query.clear_ordering(force=True)
  1046. obj.query.add_ordering(*order_by)
  1047. return obj.get()
  1048. def earliest(self, *fields):
  1049. if self.query.is_sliced:
  1050. raise TypeError("Cannot change a query once a slice has been taken.")
  1051. return self._earliest(*fields)
  1052. async def aearliest(self, *fields):
  1053. return await sync_to_async(self.earliest)(*fields)
  1054. def latest(self, *fields):
  1055. """
  1056. Return the latest object according to fields (if given) or by the
  1057. model's Meta.get_latest_by.
  1058. """
  1059. if self.query.is_sliced:
  1060. raise TypeError("Cannot change a query once a slice has been taken.")
  1061. return self.reverse()._earliest(*fields)
  1062. async def alatest(self, *fields):
  1063. return await sync_to_async(self.latest)(*fields)
  1064. def first(self):
  1065. """Return the first object of a query or None if no match is found."""
  1066. if self.ordered or not self.query.default_ordering:
  1067. queryset = self
  1068. else:
  1069. self._check_ordering_first_last_queryset_aggregation(method="first")
  1070. queryset = self.order_by("pk")
  1071. for obj in queryset[:1]:
  1072. return obj
  1073. async def afirst(self):
  1074. return await sync_to_async(self.first)()
  1075. def last(self):
  1076. """Return the last object of a query or None if no match is found."""
  1077. if self.ordered or not self.query.default_ordering:
  1078. queryset = self.reverse()
  1079. else:
  1080. self._check_ordering_first_last_queryset_aggregation(method="last")
  1081. queryset = self.order_by("-pk")
  1082. for obj in queryset[:1]:
  1083. return obj
  1084. async def alast(self):
  1085. return await sync_to_async(self.last)()
  1086. def in_bulk(self, id_list=None, *, field_name="pk"):
  1087. """
  1088. Return a dictionary mapping each of the given IDs to the object with
  1089. that ID. If `id_list` isn't provided, evaluate the entire QuerySet.
  1090. """
  1091. if self.query.is_sliced:
  1092. raise TypeError("Cannot use 'limit' or 'offset' with in_bulk().")
  1093. if id_list is not None and not id_list:
  1094. return {}
  1095. opts = self.model._meta
  1096. unique_fields = [
  1097. constraint.fields[0]
  1098. for constraint in opts.total_unique_constraints
  1099. if len(constraint.fields) == 1
  1100. ]
  1101. if (
  1102. field_name != "pk"
  1103. and not opts.get_field(field_name).unique
  1104. and field_name not in unique_fields
  1105. and self.query.distinct_fields != (field_name,)
  1106. ):
  1107. raise ValueError(
  1108. "in_bulk()'s field_name must be a unique field but %r isn't."
  1109. % field_name
  1110. )
  1111. qs = self
  1112. def get_obj(obj):
  1113. return obj
  1114. if issubclass(self._iterable_class, ModelIterable):
  1115. # Raise an AttributeError if field_name is deferred.
  1116. get_key = operator.attrgetter(field_name)
  1117. elif issubclass(self._iterable_class, ValuesIterable):
  1118. if field_name not in self.query.values_select:
  1119. qs = qs.values(field_name, *self.query.values_select)
  1120. def get_obj(obj): # noqa: F811
  1121. # We can safely mutate the dictionaries returned by
  1122. # ValuesIterable here, since they are limited to the scope
  1123. # of this function, and get_key runs before get_obj.
  1124. del obj[field_name]
  1125. return obj
  1126. get_key = operator.itemgetter(field_name)
  1127. elif issubclass(self._iterable_class, ValuesListIterable):
  1128. try:
  1129. field_index = self.query.values_select.index(field_name)
  1130. except ValueError:
  1131. # field_name is missing from values_select, so add it.
  1132. field_index = 0
  1133. if issubclass(self._iterable_class, NamedValuesListIterable):
  1134. kwargs = {"named": True}
  1135. else:
  1136. kwargs = {}
  1137. get_obj = operator.itemgetter(slice(1, None))
  1138. qs = qs.values_list(field_name, *self.query.values_select, **kwargs)
  1139. get_key = operator.itemgetter(field_index)
  1140. elif issubclass(self._iterable_class, FlatValuesListIterable):
  1141. if self.query.values_select == (field_name,):
  1142. # Mapping field_name to itself.
  1143. get_key = get_obj
  1144. else:
  1145. # Transform it back into a non-flat values_list().
  1146. qs = qs.values_list(field_name, *self.query.values_select)
  1147. get_key = operator.itemgetter(0)
  1148. get_obj = operator.itemgetter(1)
  1149. else:
  1150. raise TypeError(
  1151. f"in_bulk() cannot be used with {self._iterable_class.__name__}."
  1152. )
  1153. if id_list is not None:
  1154. filter_key = "{}__in".format(field_name)
  1155. id_list = tuple(id_list)
  1156. batch_size = connections[self.db].ops.bulk_batch_size([opts.pk], id_list)
  1157. # If the database has a limit on the number of query parameters
  1158. # (e.g. SQLite), retrieve objects in batches if necessary.
  1159. if batch_size and batch_size < len(id_list):
  1160. results = ()
  1161. for offset in range(0, len(id_list), batch_size):
  1162. batch = id_list[offset : offset + batch_size]
  1163. results += tuple(qs.filter(**{filter_key: batch}))
  1164. qs = results
  1165. else:
  1166. qs = qs.filter(**{filter_key: id_list})
  1167. else:
  1168. qs = qs._chain()
  1169. return {get_key(obj): get_obj(obj) for obj in qs}
  1170. async def ain_bulk(self, id_list=None, *, field_name="pk"):
  1171. return await sync_to_async(self.in_bulk)(
  1172. id_list=id_list,
  1173. field_name=field_name,
  1174. )
  1175. def delete(self):
  1176. """Delete the records in the current QuerySet."""
  1177. self._not_support_combined_queries("delete")
  1178. if self.query.is_sliced:
  1179. raise TypeError("Cannot use 'limit' or 'offset' with delete().")
  1180. if self.query.distinct_fields:
  1181. raise TypeError("Cannot call delete() after .distinct(*fields).")
  1182. if self._fields is not None:
  1183. raise TypeError("Cannot call delete() after .values() or .values_list()")
  1184. del_query = self._chain()
  1185. # The delete is actually 2 queries - one to find related objects,
  1186. # and one to delete. Make sure that the discovery of related
  1187. # objects is performed on the same database as the deletion.
  1188. del_query._for_write = True
  1189. # Disable non-supported fields.
  1190. del_query.query.select_for_update = False
  1191. del_query.query.select_related = False
  1192. del_query.query.clear_ordering(force=True)
  1193. collector = Collector(using=del_query.db, origin=self)
  1194. collector.collect(del_query)
  1195. num_deleted, num_deleted_per_model = collector.delete()
  1196. # Clear the result cache, in case this QuerySet gets reused.
  1197. self._result_cache = None
  1198. return num_deleted, num_deleted_per_model
  1199. delete.alters_data = True
  1200. delete.queryset_only = True
  1201. async def adelete(self):
  1202. return await sync_to_async(self.delete)()
  1203. adelete.alters_data = True
  1204. adelete.queryset_only = True
  1205. def _raw_delete(self, using):
  1206. """
  1207. Delete objects found from the given queryset in single direct SQL
  1208. query. No signals are sent and there is no protection for cascades.
  1209. """
  1210. query = self.query.clone()
  1211. query.__class__ = sql.DeleteQuery
  1212. return query.get_compiler(using).execute_sql(ROW_COUNT)
  1213. _raw_delete.alters_data = True
  1214. def update(self, **kwargs):
  1215. """
  1216. Update all elements in the current QuerySet, setting all the given
  1217. fields to the appropriate values.
  1218. """
  1219. self._not_support_combined_queries("update")
  1220. if self.query.is_sliced:
  1221. raise TypeError("Cannot update a query once a slice has been taken.")
  1222. if self.query.distinct_fields:
  1223. raise TypeError("Cannot call update() after .distinct(*fields).")
  1224. self._for_write = True
  1225. query = self.query.chain(sql.UpdateQuery)
  1226. query.add_update_values(kwargs)
  1227. # Inline annotations in order_by(), if possible.
  1228. new_order_by = []
  1229. for col in query.order_by:
  1230. alias = col
  1231. descending = False
  1232. if isinstance(alias, str) and alias.startswith("-"):
  1233. alias = alias.removeprefix("-")
  1234. descending = True
  1235. if annotation := query.annotations.get(alias):
  1236. if getattr(annotation, "contains_aggregate", False):
  1237. raise exceptions.FieldError(
  1238. f"Cannot update when ordering by an aggregate: {annotation}"
  1239. )
  1240. if descending:
  1241. annotation = annotation.desc()
  1242. new_order_by.append(annotation)
  1243. else:
  1244. new_order_by.append(col)
  1245. query.order_by = tuple(new_order_by)
  1246. # Clear SELECT clause as all annotation references were inlined by
  1247. # add_update_values() already.
  1248. query.clear_select_clause()
  1249. with transaction.mark_for_rollback_on_error(using=self.db):
  1250. rows = query.get_compiler(self.db).execute_sql(ROW_COUNT)
  1251. self._result_cache = None
  1252. return rows
  1253. update.alters_data = True
  1254. async def aupdate(self, **kwargs):
  1255. return await sync_to_async(self.update)(**kwargs)
  1256. aupdate.alters_data = True
  1257. def _update(self, values, returning_fields=None):
  1258. """
  1259. A version of update() that accepts field objects instead of field
  1260. names. Used primarily for model saving and not intended for use by
  1261. general code (it requires too much poking around at model internals to
  1262. be useful at that level).
  1263. """
  1264. if self.query.is_sliced:
  1265. raise TypeError("Cannot update a query once a slice has been taken.")
  1266. query = self.query.chain(sql.UpdateQuery)
  1267. query.add_update_fields(values)
  1268. # Clear any annotations so that they won't be present in subqueries.
  1269. query.annotations = {}
  1270. self._result_cache = None
  1271. if returning_fields is None:
  1272. return query.get_compiler(self.db).execute_sql(ROW_COUNT)
  1273. return query.get_compiler(self.db).execute_returning_sql(returning_fields)
  1274. _update.alters_data = True
  1275. _update.queryset_only = False
  1276. def exists(self):
  1277. """
  1278. Return True if the QuerySet would have any results, False otherwise.
  1279. """
  1280. if self._result_cache is None:
  1281. return self.query.has_results(using=self.db)
  1282. return bool(self._result_cache)
  1283. async def aexists(self):
  1284. return await sync_to_async(self.exists)()
  1285. def contains(self, obj):
  1286. """
  1287. Return True if the QuerySet contains the provided obj,
  1288. False otherwise.
  1289. """
  1290. self._not_support_combined_queries("contains")
  1291. if self._fields is not None:
  1292. raise TypeError(
  1293. "Cannot call QuerySet.contains() after .values() or .values_list()."
  1294. )
  1295. try:
  1296. if obj._meta.concrete_model != self.model._meta.concrete_model:
  1297. return False
  1298. except AttributeError:
  1299. raise TypeError("'obj' must be a model instance.")
  1300. if not obj._is_pk_set():
  1301. raise ValueError("QuerySet.contains() cannot be used on unsaved objects.")
  1302. if self._result_cache is not None:
  1303. return obj in self._result_cache
  1304. return self.filter(pk=obj.pk).exists()
  1305. async def acontains(self, obj):
  1306. return await sync_to_async(self.contains)(obj=obj)
  1307. def _prefetch_related_objects(self):
  1308. # This method can only be called once the result cache has been filled.
  1309. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)
  1310. self._prefetch_done = True
  1311. def explain(self, *, format=None, **options):
  1312. """
  1313. Runs an EXPLAIN on the SQL query this QuerySet would perform, and
  1314. returns the results.
  1315. """
  1316. return self.query.explain(using=self.db, format=format, **options)
  1317. async def aexplain(self, *, format=None, **options):
  1318. return await sync_to_async(self.explain)(format=format, **options)
  1319. ##################################################
  1320. # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
  1321. ##################################################
  1322. def raw(self, raw_query, params=(), translations=None, using=None):
  1323. if using is None:
  1324. using = self.db
  1325. qs = RawQuerySet(
  1326. raw_query,
  1327. model=self.model,
  1328. params=params,
  1329. translations=translations,
  1330. using=using,
  1331. fetch_mode=self._fetch_mode,
  1332. )
  1333. qs._prefetch_related_lookups = self._prefetch_related_lookups[:]
  1334. return qs
  1335. def _values(self, *fields, **expressions):
  1336. clone = self._chain()
  1337. if expressions:
  1338. # RemovedInDjango70Warning: When the deprecation ends, deindent as:
  1339. # clone = clone.annotate(**expressions)
  1340. with warnings.catch_warnings(
  1341. action="ignore", category=RemovedInDjango70Warning
  1342. ):
  1343. clone = clone.annotate(**expressions)
  1344. clone._fields = fields
  1345. clone.query.set_values(fields)
  1346. return clone
  1347. def values(self, *fields, **expressions):
  1348. fields += tuple(expressions)
  1349. clone = self._values(*fields, **expressions)
  1350. clone._iterable_class = ValuesIterable
  1351. return clone
  1352. def values_list(self, *fields, flat=False, named=False):
  1353. if flat and named:
  1354. raise TypeError("'flat' and 'named' can't be used together.")
  1355. if flat:
  1356. if len(fields) > 1:
  1357. raise TypeError(
  1358. "'flat' is not valid when values_list is called with more than one "
  1359. "field."
  1360. )
  1361. elif not fields:
  1362. # RemovedInDjango70Warning: When the deprecation ends, replace
  1363. # with:
  1364. # raise TypeError(
  1365. # "'flat' is not valid when values_list is called with no "
  1366. # "fields."
  1367. # )
  1368. warnings.warn(
  1369. "Calling values_list() with no field name and flat=True "
  1370. "is deprecated. Pass an explicit field name instead, like "
  1371. "'pk'.",
  1372. RemovedInDjango70Warning,
  1373. )
  1374. fields = [self.model._meta.concrete_fields[0].attname]
  1375. field_names = {f: False for f in fields if not hasattr(f, "resolve_expression")}
  1376. _fields = []
  1377. expressions = {}
  1378. counter = 1
  1379. for field in fields:
  1380. field_name = field
  1381. expression = None
  1382. if hasattr(field, "resolve_expression"):
  1383. field_name = getattr(
  1384. field, "default_alias", field.__class__.__name__.lower()
  1385. )
  1386. expression = field
  1387. # For backward compatibility reasons expressions are always
  1388. # prefixed with the counter even if their default alias doesn't
  1389. # collide with field names. Changing this logic could break
  1390. # some usage of named=True.
  1391. seen = True
  1392. elif seen := field_names[field_name]:
  1393. expression = F(field_name)
  1394. if seen:
  1395. field_name_prefix = field_name
  1396. while (field_name := f"{field_name_prefix}{counter}") in field_names:
  1397. counter += 1
  1398. if expression is not None:
  1399. expressions[field_name] = expression
  1400. field_names[field_name] = True
  1401. _fields.append(field_name)
  1402. clone = self._values(*_fields, **expressions)
  1403. clone._iterable_class = (
  1404. NamedValuesListIterable
  1405. if named
  1406. else FlatValuesListIterable if flat else ValuesListIterable
  1407. )
  1408. return clone
  1409. def dates(self, field_name, kind, order="ASC"):
  1410. """
  1411. Return a list of date objects representing all available dates for
  1412. the given field_name, scoped to 'kind'.
  1413. """
  1414. if kind not in ("year", "month", "week", "day"):
  1415. raise ValueError("'kind' must be one of 'year', 'month', 'week', or 'day'.")
  1416. if order not in ("ASC", "DESC"):
  1417. raise ValueError("'order' must be either 'ASC' or 'DESC'.")
  1418. return (
  1419. self.annotate(
  1420. datefield=Trunc(field_name, kind, output_field=DateField()),
  1421. plain_field=F(field_name),
  1422. )
  1423. .values_list("datefield", flat=True)
  1424. .distinct()
  1425. .filter(plain_field__isnull=False)
  1426. .order_by(("-" if order == "DESC" else "") + "datefield")
  1427. )
  1428. def datetimes(self, field_name, kind, order="ASC", tzinfo=None):
  1429. """
  1430. Return a list of datetime objects representing all available
  1431. datetimes for the given field_name, scoped to 'kind'.
  1432. """
  1433. if kind not in ("year", "month", "week", "day", "hour", "minute", "second"):
  1434. raise ValueError(
  1435. "'kind' must be one of 'year', 'month', 'week', 'day', "
  1436. "'hour', 'minute', or 'second'."
  1437. )
  1438. if order not in ("ASC", "DESC"):
  1439. raise ValueError("'order' must be either 'ASC' or 'DESC'.")
  1440. if settings.USE_TZ:
  1441. if tzinfo is None:
  1442. tzinfo = timezone.get_current_timezone()
  1443. else:
  1444. tzinfo = None
  1445. return (
  1446. self.annotate(
  1447. datetimefield=Trunc(
  1448. field_name,
  1449. kind,
  1450. output_field=DateTimeField(),
  1451. tzinfo=tzinfo,
  1452. ),
  1453. plain_field=F(field_name),
  1454. )
  1455. .values_list("datetimefield", flat=True)
  1456. .distinct()
  1457. .filter(plain_field__isnull=False)
  1458. .order_by(("-" if order == "DESC" else "") + "datetimefield")
  1459. )
  1460. def none(self):
  1461. """Return an empty QuerySet."""
  1462. clone = self._chain()
  1463. clone.query.set_empty()
  1464. return clone
  1465. ##################################################################
  1466. # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
  1467. ##################################################################
  1468. def all(self):
  1469. """
  1470. Return a new QuerySet that is a copy of the current one. This allows a
  1471. QuerySet to proxy for a model manager in some cases.
  1472. """
  1473. return self._chain()
  1474. def filter(self, *args, **kwargs):
  1475. """
  1476. Return a new QuerySet instance with the args ANDed to the existing
  1477. set.
  1478. """
  1479. self._not_support_combined_queries("filter")
  1480. return self._filter_or_exclude(False, args, kwargs)
  1481. def exclude(self, *args, **kwargs):
  1482. """
  1483. Return a new QuerySet instance with NOT (args) ANDed to the existing
  1484. set.
  1485. """
  1486. self._not_support_combined_queries("exclude")
  1487. return self._filter_or_exclude(True, args, kwargs)
  1488. def _filter_or_exclude(self, negate, args, kwargs):
  1489. if (args or kwargs) and self.query.is_sliced:
  1490. raise TypeError("Cannot filter a query once a slice has been taken.")
  1491. clone = self._chain()
  1492. if self._defer_next_filter:
  1493. self._defer_next_filter = False
  1494. clone._deferred_filter = negate, args, kwargs
  1495. else:
  1496. clone._filter_or_exclude_inplace(negate, args, kwargs)
  1497. return clone
  1498. def _filter_or_exclude_inplace(self, negate, args, kwargs):
  1499. if invalid_kwargs := PROHIBITED_FILTER_KWARGS.intersection(kwargs):
  1500. invalid_kwargs_str = ", ".join(f"'{k}'" for k in sorted(invalid_kwargs))
  1501. raise TypeError(f"The following kwargs are invalid: {invalid_kwargs_str}")
  1502. if negate:
  1503. self._query.add_q(~Q(*args, **kwargs))
  1504. else:
  1505. self._query.add_q(Q(*args, **kwargs))
  1506. def complex_filter(self, filter_obj):
  1507. """
  1508. Return a new QuerySet instance with filter_obj added to the filters.
  1509. filter_obj can be a Q object or a dictionary of keyword lookup
  1510. arguments.
  1511. This exists to support framework features such as 'limit_choices_to',
  1512. and usually it will be more natural to use other methods.
  1513. """
  1514. if isinstance(filter_obj, Q):
  1515. clone = self._chain()
  1516. clone.query.add_q(filter_obj)
  1517. return clone
  1518. else:
  1519. return self._filter_or_exclude(False, args=(), kwargs=filter_obj)
  1520. def _combinator_query(self, combinator, *other_qs, all=False):
  1521. # Clone the query to inherit the select list and everything
  1522. clone = self._chain()
  1523. # Clear limits and ordering so they can be reapplied
  1524. clone.query.clear_ordering(force=True)
  1525. clone.query.default_ordering = True
  1526. self._clear_ordering_in_combined_queries(clone.query, other_qs)
  1527. clone.query.clear_limits()
  1528. clone.query.combinator = combinator
  1529. clone.query.combinator_all = all
  1530. return clone
  1531. def union(self, *other_qs, all=False):
  1532. # If the query is an EmptyQuerySet, combine all nonempty querysets.
  1533. if isinstance(self, EmptyQuerySet):
  1534. qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]
  1535. if not qs:
  1536. return self
  1537. if len(qs) == 1:
  1538. return qs[0]
  1539. return qs[0]._combinator_query("union", *qs[1:], all=all)
  1540. elif not other_qs:
  1541. return self
  1542. return self._combinator_query("union", *other_qs, all=all)
  1543. def intersection(self, *other_qs):
  1544. # If any query is an EmptyQuerySet, return it.
  1545. if isinstance(self, EmptyQuerySet):
  1546. return self
  1547. for other in other_qs:
  1548. if isinstance(other, EmptyQuerySet):
  1549. return other
  1550. return self._combinator_query("intersection", *other_qs)
  1551. def difference(self, *other_qs):
  1552. # If the query is an EmptyQuerySet, return it.
  1553. if isinstance(self, EmptyQuerySet):
  1554. return self
  1555. return self._combinator_query("difference", *other_qs)
  1556. def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False):
  1557. """
  1558. Return a new QuerySet instance that will select objects with a
  1559. FOR UPDATE lock.
  1560. """
  1561. if nowait and skip_locked:
  1562. raise ValueError("The nowait option cannot be used with skip_locked.")
  1563. obj = self._chain()
  1564. obj._for_write = True
  1565. obj.query.select_for_update = True
  1566. obj.query.select_for_update_nowait = nowait
  1567. obj.query.select_for_update_skip_locked = skip_locked
  1568. obj.query.select_for_update_of = of
  1569. obj.query.select_for_no_key_update = no_key
  1570. return obj
  1571. def select_related(self, *fields):
  1572. """
  1573. Return a new QuerySet instance that will select related objects.
  1574. If fields are specified, they must be ForeignKey fields and only those
  1575. related objects are included in the selection.
  1576. If select_related(None) is called, clear the list.
  1577. """
  1578. self._not_support_combined_queries("select_related")
  1579. if self._fields is not None:
  1580. raise TypeError(
  1581. "Cannot call select_related() after .values() or .values_list()"
  1582. )
  1583. obj = self._chain()
  1584. if fields == (None,):
  1585. obj.query.select_related = False
  1586. elif fields:
  1587. obj.query.add_select_related(fields)
  1588. else:
  1589. # RemovedInDjango70Warning: when the deprecation ends, raise a
  1590. # TypeError instead.
  1591. warn_about_external_use(
  1592. "Calling select_related() with no arguments is deprecated. "
  1593. "Specify the fields to fetch instead.",
  1594. category=RemovedInDjango70Warning,
  1595. skip_name_prefixes=("django.db.models",),
  1596. )
  1597. obj.query.select_related = True
  1598. return obj
  1599. def prefetch_related(self, *lookups):
  1600. """
  1601. Return a new QuerySet instance that will prefetch the specified
  1602. Many-To-One and Many-To-Many related objects when the QuerySet is
  1603. evaluated.
  1604. When prefetch_related() is called more than once, append to the list of
  1605. prefetch lookups. If prefetch_related(None) is called, clear the list.
  1606. """
  1607. self._not_support_combined_queries("prefetch_related")
  1608. clone = self._chain()
  1609. if lookups == (None,):
  1610. clone._prefetch_related_lookups = ()
  1611. else:
  1612. for lookup in lookups:
  1613. if isinstance(lookup, Prefetch):
  1614. lookup = lookup.prefetch_to
  1615. lookup = lookup.split(LOOKUP_SEP, 1)[0]
  1616. if lookup in self.query._filtered_relations:
  1617. raise ValueError(
  1618. "prefetch_related() is not supported with FilteredRelation."
  1619. )
  1620. clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups
  1621. return clone
  1622. def annotate(self, *args, **kwargs):
  1623. """
  1624. Return a query set in which the returned objects have been annotated
  1625. with extra data or aggregations.
  1626. """
  1627. self._not_support_combined_queries("annotate")
  1628. return self._annotate(args, kwargs, select=True)
  1629. def alias(self, *args, **kwargs):
  1630. """
  1631. Return a query set with added aliases for extra data or aggregations.
  1632. """
  1633. self._not_support_combined_queries("alias")
  1634. return self._annotate(args, kwargs, select=False)
  1635. def _annotate(self, args, kwargs, select=True):
  1636. self._validate_values_are_expressions(
  1637. args + tuple(kwargs.values()), method_name="annotate"
  1638. )
  1639. annotations = {}
  1640. for arg in args:
  1641. # The default_alias property raises TypeError if default_alias
  1642. # can't be set automatically or AttributeError if it isn't an
  1643. # attribute.
  1644. try:
  1645. if arg.default_alias in kwargs:
  1646. raise ValueError(
  1647. "The named annotation '%s' conflicts with the "
  1648. "default name for another annotation." % arg.default_alias
  1649. )
  1650. except (TypeError, AttributeError):
  1651. raise TypeError("Complex annotations require an alias")
  1652. annotations[arg.default_alias] = arg
  1653. annotations.update(kwargs)
  1654. clone = self._chain()
  1655. names = self._fields
  1656. if names is None:
  1657. names = set(
  1658. chain.from_iterable(
  1659. (
  1660. (field.name, field.attname)
  1661. if hasattr(field, "attname")
  1662. else (field.name,)
  1663. )
  1664. for field in self.model._meta.get_fields()
  1665. )
  1666. )
  1667. for alias, annotation in annotations.items():
  1668. if alias in names:
  1669. raise ValueError(
  1670. "The annotation '%s' conflicts with a field on "
  1671. "the model." % alias
  1672. )
  1673. if isinstance(annotation, FilteredRelation):
  1674. clone.query.add_filtered_relation(annotation, alias)
  1675. else:
  1676. clone.query.add_annotation(
  1677. annotation,
  1678. alias,
  1679. select=select,
  1680. )
  1681. for alias, annotation in clone.query.annotations.items():
  1682. if alias in annotations and annotation.contains_aggregate:
  1683. if clone._fields is None:
  1684. clone.query.group_by = True
  1685. else:
  1686. clone.query.set_group_by()
  1687. break
  1688. return clone
  1689. def order_by(self, *field_names):
  1690. """Return a new QuerySet instance with the ordering changed."""
  1691. if self.query.is_sliced:
  1692. raise TypeError("Cannot reorder a query once a slice has been taken.")
  1693. obj = self._chain()
  1694. obj.query.clear_ordering(force=True, clear_default=False)
  1695. obj.query.add_ordering(*field_names)
  1696. return obj
  1697. def distinct(self, *field_names):
  1698. """
  1699. Return a new QuerySet instance that will select only distinct results.
  1700. """
  1701. self._not_support_combined_queries("distinct")
  1702. if self.query.is_sliced:
  1703. raise TypeError(
  1704. "Cannot create distinct fields once a slice has been taken."
  1705. )
  1706. obj = self._chain()
  1707. obj.query.add_distinct_fields(*field_names)
  1708. return obj
  1709. def extra(
  1710. self,
  1711. select=None,
  1712. where=None,
  1713. params=None,
  1714. tables=None,
  1715. order_by=None,
  1716. select_params=None,
  1717. ):
  1718. """Add extra SQL fragments to the query."""
  1719. self._not_support_combined_queries("extra")
  1720. if self.query.is_sliced:
  1721. raise TypeError("Cannot change a query once a slice has been taken.")
  1722. clone = self._chain()
  1723. clone.query.add_extra(select, select_params, where, params, tables, order_by)
  1724. return clone
  1725. def reverse(self):
  1726. """Reverse the ordering of the QuerySet."""
  1727. if self.query.is_sliced:
  1728. raise TypeError("Cannot reverse a query once a slice has been taken.")
  1729. clone = self._chain()
  1730. clone.query.standard_ordering = not clone.query.standard_ordering
  1731. return clone
  1732. def defer(self, *fields):
  1733. """
  1734. Defer the loading of data for certain fields until they are accessed.
  1735. Add the set of deferred fields to any existing set of deferred fields.
  1736. The only exception to this is if None is passed in as the only
  1737. parameter, in which case remove all deferrals.
  1738. """
  1739. self._not_support_combined_queries("defer")
  1740. if self._fields is not None:
  1741. raise TypeError("Cannot call defer() after .values() or .values_list()")
  1742. clone = self._chain()
  1743. if fields == (None,):
  1744. clone.query.clear_deferred_loading()
  1745. else:
  1746. clone.query.add_deferred_loading(fields)
  1747. return clone
  1748. def only(self, *fields):
  1749. """
  1750. Essentially, the opposite of defer(). Only the fields passed into this
  1751. method and that are not already specified as deferred are loaded
  1752. immediately when the queryset is evaluated.
  1753. """
  1754. self._not_support_combined_queries("only")
  1755. if self._fields is not None:
  1756. raise TypeError("Cannot call only() after .values() or .values_list()")
  1757. if fields == (None,):
  1758. # Can only pass None to defer(), not only(), as the rest option.
  1759. # That won't stop people trying to do this, so let's be explicit.
  1760. raise TypeError("Cannot pass None as an argument to only().")
  1761. for field in fields:
  1762. field = field.split(LOOKUP_SEP, 1)[0]
  1763. if field in self.query._filtered_relations:
  1764. raise ValueError("only() is not supported with FilteredRelation.")
  1765. clone = self._chain()
  1766. clone.query.add_immediate_loading(fields)
  1767. return clone
  1768. def using(self, alias):
  1769. """Select which database this QuerySet should execute against."""
  1770. clone = self._chain()
  1771. clone._db = alias
  1772. return clone
  1773. def fetch_mode(self, fetch_mode):
  1774. """Set the fetch mode for the QuerySet."""
  1775. clone = self._chain()
  1776. clone._fetch_mode = fetch_mode
  1777. return clone
  1778. ###################################
  1779. # PUBLIC INTROSPECTION ATTRIBUTES #
  1780. ###################################
  1781. @property
  1782. def ordered(self):
  1783. """
  1784. Return True if the QuerySet is ordered -- i.e. has an order_by()
  1785. clause or a default ordering on the model (or is empty).
  1786. """
  1787. if isinstance(self, EmptyQuerySet):
  1788. return True
  1789. if self.query.extra_order_by or self.query.order_by:
  1790. return True
  1791. elif (
  1792. self.query.default_ordering
  1793. and self.query.get_meta().ordering
  1794. and
  1795. # A default ordering doesn't affect GROUP BY queries.
  1796. not self.query.group_by
  1797. ):
  1798. return True
  1799. else:
  1800. return False
  1801. @property
  1802. def totally_ordered(self):
  1803. """
  1804. Returns True if the QuerySet is ordered and the ordering is
  1805. deterministic. This requires that the ordering includes a field
  1806. (or set of fields) that is unique and non-nullable.
  1807. For queries involving a GROUP BY clause, the model's default
  1808. ordering is ignored. Ordering specified via .extra(order_by=...)
  1809. is also ignored.
  1810. """
  1811. if not self.ordered:
  1812. return False
  1813. ordering = self.query.order_by
  1814. if not ordering and self.query.default_ordering:
  1815. ordering = self.query.get_meta().ordering
  1816. if not ordering:
  1817. return False
  1818. opts = self.model._meta
  1819. pk_fields = {f.attname for f in opts.pk_fields}
  1820. ordering_fields = set()
  1821. for part in ordering:
  1822. # Search for single field providing a total ordering.
  1823. field_name = None
  1824. if isinstance(part, str):
  1825. field_name = part.lstrip("-")
  1826. elif isinstance(part, F):
  1827. field_name = part.name
  1828. elif isinstance(part, OrderBy) and isinstance(part.expression, F):
  1829. field_name = part.expression.name
  1830. if field_name:
  1831. if field_name == "pk":
  1832. return True
  1833. # Normalize attname references by using get_field().
  1834. try:
  1835. field = opts.get_field(field_name)
  1836. except exceptions.FieldDoesNotExist:
  1837. # Could be "?" for random ordering or a related field
  1838. # lookup. Skip this part of introspection for now.
  1839. continue
  1840. # Ordering by a related field name orders by the referenced
  1841. # model's ordering. Skip this part of introspection for now.
  1842. if field.remote_field and field_name == field.name:
  1843. continue
  1844. if field.attname in pk_fields and len(pk_fields) == 1:
  1845. return True
  1846. if field.unique and not field.null:
  1847. return True
  1848. ordering_fields.add(field.attname)
  1849. # Account for members of a CompositePrimaryKey.
  1850. if ordering_fields.issuperset(pk_fields):
  1851. return True
  1852. # No single total ordering field, try unique_together and total
  1853. # unique constraints.
  1854. constraint_field_names = (
  1855. *opts.unique_together,
  1856. *(constraint.fields for constraint in opts.total_unique_constraints),
  1857. )
  1858. for field_names in constraint_field_names:
  1859. # Normalize attname references by using get_field().
  1860. try:
  1861. fields = [opts.get_field(field_name) for field_name in field_names]
  1862. except exceptions.FieldDoesNotExist:
  1863. continue
  1864. # Composite unique constraints containing a nullable column
  1865. # cannot ensure total ordering.
  1866. if any(field.null for field in fields):
  1867. continue
  1868. if ordering_fields.issuperset(field.attname for field in fields):
  1869. return True
  1870. return False
  1871. @property
  1872. def db(self):
  1873. """Return the database used if this query is executed now."""
  1874. if self._for_write:
  1875. return self._db or router.db_for_write(self.model, **self._hints)
  1876. return self._db or router.db_for_read(self.model, **self._hints)
  1877. ###################
  1878. # PRIVATE METHODS #
  1879. ###################
  1880. def _insert(
  1881. self,
  1882. objs,
  1883. fields,
  1884. returning_fields=None,
  1885. raw=False,
  1886. using=None,
  1887. on_conflict=None,
  1888. update_fields=None,
  1889. unique_fields=None,
  1890. ):
  1891. """
  1892. Insert a new record for the given model. This provides an interface to
  1893. the InsertQuery class and is how Model.save() is implemented.
  1894. """
  1895. self._for_write = True
  1896. if using is None:
  1897. using = self.db
  1898. query = sql.InsertQuery(
  1899. self.model,
  1900. on_conflict=on_conflict,
  1901. update_fields=update_fields,
  1902. unique_fields=unique_fields,
  1903. )
  1904. query.insert_values(fields, objs, raw=raw)
  1905. return query.get_compiler(using=using).execute_sql(returning_fields)
  1906. _insert.alters_data = True
  1907. _insert.queryset_only = False
  1908. def _batched_insert(
  1909. self,
  1910. objs,
  1911. fields,
  1912. batch_size,
  1913. on_conflict=None,
  1914. update_fields=None,
  1915. unique_fields=None,
  1916. ):
  1917. """
  1918. Helper method for bulk_create() to insert objs one batch at a time.
  1919. """
  1920. connection = connections[self.db]
  1921. ops = connection.ops
  1922. max_batch_size = max(ops.bulk_batch_size(fields, objs), 1)
  1923. batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size
  1924. inserted_rows = []
  1925. returning_fields = (
  1926. self.model._meta.db_returning_fields
  1927. if (
  1928. connection.features.can_return_rows_from_bulk_insert
  1929. and (on_conflict is None or on_conflict == OnConflict.UPDATE)
  1930. )
  1931. else None
  1932. )
  1933. batches = [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]
  1934. if len(batches) > 1:
  1935. context = transaction.atomic(using=self.db, savepoint=False)
  1936. else:
  1937. context = nullcontext()
  1938. with context:
  1939. for item in batches:
  1940. inserted_rows.extend(
  1941. self._insert(
  1942. item,
  1943. fields=fields,
  1944. using=self.db,
  1945. on_conflict=on_conflict,
  1946. update_fields=update_fields,
  1947. unique_fields=unique_fields,
  1948. returning_fields=returning_fields,
  1949. )
  1950. )
  1951. return inserted_rows
  1952. def _disable_cloning(self):
  1953. """
  1954. Prevent calls to _chain() from creating a new QuerySet via _clone().
  1955. All subsequent QuerySet mutations will occur on this instance until
  1956. _enable_cloning() is used.
  1957. """
  1958. self._cloning_enabled = False
  1959. return self
  1960. def _enable_cloning(self):
  1961. """
  1962. Allow calls to _chain() to create a new QuerySet via _clone(). Restores
  1963. the default behavior where any QuerySet mutation will return a new
  1964. QuerySet instance. Necessary only when there has been a
  1965. _disable_cloning() call previously.
  1966. """
  1967. self._cloning_enabled = True
  1968. return self
  1969. def _avoid_cloning(self):
  1970. """
  1971. Temporarily prevent QuerySet _clone() operations, restoring the default
  1972. behavior on exit. For the duration of the context managed statement,
  1973. all operations (e.g. filter(), exclude(), etc.) will mutate the same
  1974. QuerySet instance.
  1975. @contextlib.contextmanager is intentionally not used for performance
  1976. reasons.
  1977. """
  1978. return PreventQuerySetCloning(self)
  1979. def _chain(self):
  1980. """
  1981. Return a copy of the current QuerySet that's ready for another
  1982. operation.
  1983. If the QuerySet has opted in to in-place mutations via
  1984. _disable_cloning() temporarily, the copy doesn't occur and instead the
  1985. same QuerySet instance will be modified.
  1986. """
  1987. if not self._cloning_enabled:
  1988. obj = self
  1989. else:
  1990. obj = self._clone()
  1991. if obj._sticky_filter:
  1992. obj.query.filter_is_sticky = True
  1993. obj._sticky_filter = False
  1994. return obj
  1995. def _clone(self):
  1996. """
  1997. Return a copy of the current QuerySet. A lightweight alternative
  1998. to deepcopy().
  1999. """
  2000. c = self.__class__(
  2001. model=self.model,
  2002. query=self.query.chain(),
  2003. using=self._db,
  2004. hints=self._hints,
  2005. )
  2006. c._sticky_filter = self._sticky_filter
  2007. c._for_write = self._for_write
  2008. c._prefetch_related_lookups = self._prefetch_related_lookups[:]
  2009. c._known_related_objects = self._known_related_objects
  2010. c._iterable_class = self._iterable_class
  2011. c._fetch_mode = self._fetch_mode
  2012. c._fields = self._fields
  2013. return c
  2014. def _fetch_all(self):
  2015. if self._result_cache is None:
  2016. self._result_cache = list(self._iterable_class(self))
  2017. if self._prefetch_related_lookups and not self._prefetch_done:
  2018. self._prefetch_related_objects()
  2019. def _next_is_sticky(self):
  2020. """
  2021. Indicate that the next filter call and the one following that should
  2022. be treated as a single filter. This is only important when it comes to
  2023. determining when to reuse tables for many-to-many filters. Required so
  2024. that we can filter naturally on the results of related managers.
  2025. This doesn't return a clone of the current QuerySet (it returns
  2026. "self"). The method is only used internally and should be immediately
  2027. followed by a filter() that does create a clone.
  2028. """
  2029. self._sticky_filter = True
  2030. return self
  2031. def _merge_sanity_check(self, other):
  2032. """Check that two QuerySet classes may be merged."""
  2033. if self._fields is not None and (
  2034. set(self.query.values_select) != set(other.query.values_select)
  2035. or set(self.query.extra_select) != set(other.query.extra_select)
  2036. or set(self.query.annotation_select) != set(other.query.annotation_select)
  2037. ):
  2038. raise TypeError(
  2039. "Merging '%s' classes must involve the same values in each case."
  2040. % self.__class__.__name__
  2041. )
  2042. def _merge_known_related_objects(self, other):
  2043. """
  2044. Keep track of all known related objects from either QuerySet instance.
  2045. """
  2046. for field, objects in other._known_related_objects.items():
  2047. self._known_related_objects.setdefault(field, {}).update(objects)
  2048. def resolve_expression(self, *args, **kwargs):
  2049. query = self.query.resolve_expression(*args, **kwargs)
  2050. query._db = self._db
  2051. return query
  2052. resolve_expression.queryset_only = True
  2053. def _add_hints(self, **hints):
  2054. """
  2055. Update hinting information for use by routers. Add new key/values or
  2056. overwrite existing key/values.
  2057. """
  2058. self._hints.update(hints)
  2059. def _has_filters(self):
  2060. """
  2061. Check if this QuerySet has any filtering going on. This isn't
  2062. equivalent with checking if all objects are present in results, for
  2063. example, qs[1:]._has_filters() -> False.
  2064. """
  2065. return self.query.has_filters()
  2066. @staticmethod
  2067. def _validate_values_are_expressions(values, method_name):
  2068. invalid_args = sorted(
  2069. str(arg) for arg in values if not hasattr(arg, "resolve_expression")
  2070. )
  2071. if invalid_args:
  2072. raise TypeError(
  2073. "QuerySet.%s() received non-expression(s): %s."
  2074. % (
  2075. method_name,
  2076. ", ".join(invalid_args),
  2077. )
  2078. )
  2079. def _not_support_combined_queries(self, operation_name):
  2080. if self.query.combinator:
  2081. raise NotSupportedError(
  2082. "Calling QuerySet.%s() after %s() is not supported."
  2083. % (operation_name, self.query.combinator)
  2084. )
  2085. def _check_operator_queryset(self, other, operator_):
  2086. if self.query.combinator or other.query.combinator:
  2087. raise TypeError(f"Cannot use {operator_} operator with combined queryset.")
  2088. def _check_ordering_first_last_queryset_aggregation(self, method):
  2089. if (
  2090. isinstance(self.query.group_by, tuple)
  2091. # Raise if the pk fields are not in the group_by.
  2092. and self.model._meta.pk
  2093. not in {col.output_field for col in self.query.group_by}
  2094. and set(self.model._meta.pk_fields).difference(
  2095. {col.target for col in self.query.group_by}
  2096. )
  2097. ):
  2098. raise TypeError(
  2099. f"Cannot use QuerySet.{method}() on an unordered queryset performing "
  2100. f"aggregation. Add an ordering with order_by()."
  2101. )
  2102. def _clear_ordering_in_combined_queries(self, cloned_query, other_qs):
  2103. combined_queries = [self.query]
  2104. for qs in other_qs:
  2105. query = qs.query.clone()
  2106. query.clear_ordering(force=False, clear_default=False)
  2107. combined_queries.append(query)
  2108. cloned_query.combined_queries = tuple(combined_queries)
  2109. class InstanceCheckMeta(type):
  2110. def __instancecheck__(self, instance):
  2111. return isinstance(instance, QuerySet) and instance.query.is_empty()
  2112. class EmptyQuerySet(metaclass=InstanceCheckMeta):
  2113. """
  2114. Marker class to checking if a queryset is empty by .none():
  2115. isinstance(qs.none(), EmptyQuerySet) -> True
  2116. """
  2117. def __init__(self, *args, **kwargs):
  2118. raise TypeError("EmptyQuerySet can't be instantiated")
  2119. class RawQuerySet:
  2120. """
  2121. Provide an iterator which converts the results of raw SQL queries into
  2122. annotated model instances.
  2123. """
  2124. def __init__(
  2125. self,
  2126. raw_query,
  2127. model=None,
  2128. query=None,
  2129. params=(),
  2130. translations=None,
  2131. using=None,
  2132. hints=None,
  2133. fetch_mode=DEFAULT_FETCH_MODE,
  2134. ):
  2135. self.raw_query = raw_query
  2136. self.model = model
  2137. self._db = using
  2138. self._hints = hints or {}
  2139. self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params)
  2140. self.params = params
  2141. self.translations = translations or {}
  2142. self._result_cache = None
  2143. self._prefetch_related_lookups = ()
  2144. self._prefetch_done = False
  2145. self._fetch_mode = fetch_mode
  2146. def resolve_model_init_order(self):
  2147. """Resolve the init field names and value positions."""
  2148. converter = connections[self.db].introspection.identifier_converter
  2149. model_init_fields = [
  2150. field
  2151. for column_name, field in self.model_fields.items()
  2152. if column_name in self.columns
  2153. ]
  2154. annotation_fields = [
  2155. (column, pos)
  2156. for pos, column in enumerate(self.columns)
  2157. if column not in self.model_fields
  2158. ]
  2159. model_init_order = [
  2160. self.columns.index(converter(f.column)) for f in model_init_fields
  2161. ]
  2162. model_init_names = [f.attname for f in model_init_fields]
  2163. return model_init_names, model_init_order, annotation_fields
  2164. def prefetch_related(self, *lookups):
  2165. """Same as QuerySet.prefetch_related()"""
  2166. clone = self._clone()
  2167. if lookups == (None,):
  2168. clone._prefetch_related_lookups = ()
  2169. else:
  2170. clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups
  2171. return clone
  2172. def _prefetch_related_objects(self):
  2173. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)
  2174. self._prefetch_done = True
  2175. def _clone(self):
  2176. """Same as QuerySet._clone()"""
  2177. c = self.__class__(
  2178. self.raw_query,
  2179. model=self.model,
  2180. query=self.query,
  2181. params=self.params,
  2182. translations=self.translations,
  2183. using=self._db,
  2184. hints=self._hints,
  2185. )
  2186. c._prefetch_related_lookups = self._prefetch_related_lookups[:]
  2187. return c
  2188. def _fetch_all(self):
  2189. if self._result_cache is None:
  2190. self._result_cache = list(self.iterator())
  2191. if self._prefetch_related_lookups and not self._prefetch_done:
  2192. self._prefetch_related_objects()
  2193. def __len__(self):
  2194. self._fetch_all()
  2195. return len(self._result_cache)
  2196. def __bool__(self):
  2197. self._fetch_all()
  2198. return bool(self._result_cache)
  2199. def __iter__(self):
  2200. self._fetch_all()
  2201. return iter(self._result_cache)
  2202. def __aiter__(self):
  2203. # Remember, __aiter__ itself is synchronous, it's the thing it returns
  2204. # that is async!
  2205. async def generator():
  2206. await sync_to_async(self._fetch_all)()
  2207. for item in self._result_cache:
  2208. yield item
  2209. return generator()
  2210. def iterator(self):
  2211. yield from RawModelIterable(self)
  2212. def __repr__(self):
  2213. return "<%s: %s>" % (self.__class__.__name__, self.query)
  2214. def __getitem__(self, k):
  2215. return list(self)[k]
  2216. @property
  2217. def db(self):
  2218. """Return the database used if this query is executed now."""
  2219. return self._db or router.db_for_read(self.model, **self._hints)
  2220. def using(self, alias):
  2221. """Select the database this RawQuerySet should execute against."""
  2222. return RawQuerySet(
  2223. self.raw_query,
  2224. model=self.model,
  2225. query=self.query.chain(using=alias),
  2226. params=self.params,
  2227. translations=self.translations,
  2228. using=alias,
  2229. fetch_mode=self._fetch_mode,
  2230. )
  2231. @cached_property
  2232. def columns(self):
  2233. """
  2234. A list of model field names in the order they'll appear in the
  2235. query results.
  2236. """
  2237. columns = self.query.get_columns()
  2238. # Adjust any column names which don't match field names
  2239. for query_name, model_name in self.translations.items():
  2240. # Ignore translations for nonexistent column names
  2241. try:
  2242. index = columns.index(query_name)
  2243. except ValueError:
  2244. pass
  2245. else:
  2246. columns[index] = model_name
  2247. return columns
  2248. @cached_property
  2249. def model_fields(self):
  2250. """A dict mapping column names to model field names."""
  2251. converter = connections[self.db].introspection.identifier_converter
  2252. return {
  2253. converter(field.column): field
  2254. for field in self.model._meta.fields
  2255. # Fields with None "column" should be ignored
  2256. # (e.g. CompositePrimaryKey).
  2257. if field.column
  2258. }
  2259. class Prefetch:
  2260. def __init__(self, lookup, queryset=None, to_attr=None):
  2261. # `prefetch_through` is the path we traverse to perform the prefetch.
  2262. self.prefetch_through = lookup
  2263. # `prefetch_to` is the path to the attribute that stores the result.
  2264. self.prefetch_to = lookup
  2265. if queryset is not None and (
  2266. isinstance(queryset, RawQuerySet)
  2267. or (
  2268. hasattr(queryset, "_iterable_class")
  2269. and not issubclass(queryset._iterable_class, ModelIterable)
  2270. )
  2271. ):
  2272. raise ValueError(
  2273. "Prefetch querysets cannot use raw(), values(), and values_list()."
  2274. )
  2275. if to_attr:
  2276. self.prefetch_to = LOOKUP_SEP.join(
  2277. lookup.split(LOOKUP_SEP)[:-1] + [to_attr]
  2278. )
  2279. self.queryset = queryset
  2280. self.to_attr = to_attr
  2281. def __getstate__(self):
  2282. obj_dict = self.__dict__.copy()
  2283. if self.queryset is not None:
  2284. queryset = self.queryset._chain()
  2285. # Prevent the QuerySet from being evaluated
  2286. queryset._result_cache = []
  2287. queryset._prefetch_done = True
  2288. obj_dict["queryset"] = queryset
  2289. return obj_dict
  2290. def add_prefix(self, prefix):
  2291. self.prefetch_through = prefix + LOOKUP_SEP + self.prefetch_through
  2292. self.prefetch_to = prefix + LOOKUP_SEP + self.prefetch_to
  2293. def get_current_prefetch_to(self, level):
  2294. return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[: level + 1])
  2295. def get_current_to_attr(self, level):
  2296. parts = self.prefetch_to.split(LOOKUP_SEP)
  2297. to_attr = parts[level]
  2298. as_attr = self.to_attr and level == len(parts) - 1
  2299. return to_attr, as_attr
  2300. def get_current_querysets(self, level):
  2301. if (
  2302. self.get_current_prefetch_to(level) == self.prefetch_to
  2303. and self.queryset is not None
  2304. ):
  2305. return [self.queryset]
  2306. return None
  2307. def __eq__(self, other):
  2308. if not isinstance(other, Prefetch):
  2309. return NotImplemented
  2310. return self.prefetch_to == other.prefetch_to
  2311. def __hash__(self):
  2312. return hash((self.__class__, self.prefetch_to))
  2313. def normalize_prefetch_lookups(lookups, prefix=None):
  2314. """Normalize lookups into Prefetch objects."""
  2315. ret = []
  2316. for lookup in lookups:
  2317. if not isinstance(lookup, Prefetch):
  2318. lookup = Prefetch(lookup)
  2319. if prefix:
  2320. lookup.add_prefix(prefix)
  2321. ret.append(lookup)
  2322. return ret
  2323. def prefetch_related_objects(model_instances, *related_lookups):
  2324. """
  2325. Populate prefetched object caches for an iterable of model instances based
  2326. on the lookups/Prefetch instances given.
  2327. """
  2328. if not model_instances:
  2329. return # nothing to do
  2330. # We need to be able to dynamically add to the list of prefetch_related
  2331. # lookups that we look up (see below). So we need some book keeping to
  2332. # ensure we don't do duplicate work.
  2333. done_queries = {} # dictionary of things like 'foo__bar': [results]
  2334. auto_lookups = set() # we add to this as we go through.
  2335. followed_descriptors = set() # recursion protection
  2336. all_lookups = normalize_prefetch_lookups(reversed(related_lookups))
  2337. while all_lookups:
  2338. lookup = all_lookups.pop()
  2339. if lookup.prefetch_to in done_queries:
  2340. if lookup.queryset is not None:
  2341. raise ValueError(
  2342. "'%s' lookup was already seen with a different queryset. "
  2343. "You may need to adjust the ordering of your lookups."
  2344. % lookup.prefetch_to
  2345. )
  2346. continue
  2347. # Top level, the list of objects to decorate is the result cache
  2348. # from the primary QuerySet. It won't be for deeper levels.
  2349. obj_list = model_instances
  2350. through_attrs = lookup.prefetch_through.split(LOOKUP_SEP)
  2351. for level, through_attr in enumerate(through_attrs):
  2352. # Prepare main instances
  2353. if not obj_list:
  2354. break
  2355. prefetch_to = lookup.get_current_prefetch_to(level)
  2356. if prefetch_to in done_queries:
  2357. # Skip any prefetching, and any object preparation
  2358. obj_list = done_queries[prefetch_to]
  2359. continue
  2360. # Prepare objects:
  2361. good_objects = True
  2362. for obj in obj_list:
  2363. # Since prefetching can re-use instances, it is possible to
  2364. # have the same instance multiple times in obj_list, so obj
  2365. # might already be prepared.
  2366. if not hasattr(obj, "_prefetched_objects_cache"):
  2367. try:
  2368. obj._prefetched_objects_cache = {}
  2369. except (AttributeError, TypeError):
  2370. # Must be an immutable object from
  2371. # values_list(flat=True), for example (TypeError) or
  2372. # a QuerySet subclass that isn't returning Model
  2373. # instances (AttributeError), either in Django or a 3rd
  2374. # party. prefetch_related() doesn't make sense, so
  2375. # quit.
  2376. good_objects = False
  2377. break
  2378. if not good_objects:
  2379. break
  2380. # Descend down tree
  2381. # We assume that objects retrieved are homogeneous (which is the
  2382. # premise of prefetch_related), so what applies to first object
  2383. # applies to all.
  2384. first_obj = next(iter(obj_list))
  2385. to_attr = lookup.get_current_to_attr(level)[0]
  2386. prefetcher, descriptor, attr_found, is_fetched = get_prefetcher(
  2387. first_obj, through_attr, to_attr
  2388. )
  2389. if not attr_found:
  2390. raise AttributeError(
  2391. "Cannot find '%s' on %s object, '%s' is an invalid "
  2392. "parameter to prefetch_related()"
  2393. % (
  2394. through_attr,
  2395. first_obj.__class__.__name__,
  2396. lookup.prefetch_through,
  2397. )
  2398. )
  2399. if level == len(through_attrs) - 1 and prefetcher is None:
  2400. # Last one, this *must* resolve to something that supports
  2401. # prefetching, otherwise there is no point adding it and the
  2402. # developer asking for it has made a mistake.
  2403. raise ValueError(
  2404. "'%s' does not resolve to an item that supports "
  2405. "prefetching - this is an invalid parameter to "
  2406. "prefetch_related()." % lookup.prefetch_through
  2407. )
  2408. obj_to_fetch = None
  2409. if prefetcher is not None:
  2410. obj_to_fetch = [obj for obj in obj_list if not is_fetched(obj)]
  2411. if obj_to_fetch:
  2412. obj_list, additional_lookups = prefetch_one_level(
  2413. obj_to_fetch,
  2414. prefetcher,
  2415. lookup,
  2416. level,
  2417. )
  2418. # We need to ensure we don't keep adding lookups from the
  2419. # same relationships to stop infinite recursion. So, if we
  2420. # are already on an automatically added lookup, don't add
  2421. # the new lookups from relationships we've seen already.
  2422. if not (
  2423. prefetch_to in done_queries
  2424. and lookup in auto_lookups
  2425. and descriptor in followed_descriptors
  2426. ):
  2427. done_queries[prefetch_to] = obj_list
  2428. new_lookups = normalize_prefetch_lookups(
  2429. reversed(additional_lookups), prefetch_to
  2430. )
  2431. auto_lookups.update(new_lookups)
  2432. all_lookups.extend(new_lookups)
  2433. followed_descriptors.add(descriptor)
  2434. else:
  2435. # Either a singly related object that has already been fetched
  2436. # (e.g. via select_related), or hopefully some other property
  2437. # that doesn't support prefetching but needs to be traversed.
  2438. # We replace the current list of parent objects with the list
  2439. # of related objects, filtering out empty or missing values so
  2440. # that we can continue with nullable or reverse relations.
  2441. new_obj_list = []
  2442. for obj in obj_list:
  2443. if through_attr in getattr(obj, "_prefetched_objects_cache", ()):
  2444. # If related objects have been prefetched, use the
  2445. # cache rather than the object's through_attr.
  2446. new_obj = list(obj._prefetched_objects_cache.get(through_attr))
  2447. else:
  2448. try:
  2449. new_obj = getattr(obj, through_attr)
  2450. except exceptions.ObjectDoesNotExist:
  2451. continue
  2452. if new_obj is None:
  2453. continue
  2454. # We special-case `list` rather than something more generic
  2455. # like `Iterable` because we don't want to accidentally
  2456. # match user models that define __iter__.
  2457. if isinstance(new_obj, list):
  2458. new_obj_list.extend(new_obj)
  2459. else:
  2460. new_obj_list.append(new_obj)
  2461. obj_list = new_obj_list
  2462. async def aprefetch_related_objects(model_instances, *related_lookups):
  2463. """See prefetch_related_objects()."""
  2464. return await sync_to_async(prefetch_related_objects)(
  2465. model_instances, *related_lookups
  2466. )
  2467. def get_prefetcher(instance, through_attr, to_attr):
  2468. """
  2469. For the attribute 'through_attr' on the given instance, find
  2470. an object that has a get_prefetch_querysets().
  2471. Return a 4 tuple containing:
  2472. (the object with get_prefetch_querysets (or None),
  2473. the descriptor object representing this relationship (or None),
  2474. a boolean that is False if the attribute was not found at all,
  2475. a function that takes an instance and returns a boolean that is True if
  2476. the attribute has already been fetched for that instance)
  2477. """
  2478. def is_to_attr_fetched(model, to_attr):
  2479. # Special case cached_property instances because hasattr() triggers
  2480. # attribute computation and assignment.
  2481. if isinstance(getattr(model, to_attr, None), cached_property):
  2482. def has_cached_property(instance):
  2483. return to_attr in instance.__dict__
  2484. return has_cached_property
  2485. def has_to_attr_attribute(instance):
  2486. return hasattr(instance, to_attr)
  2487. return has_to_attr_attribute
  2488. prefetcher = None
  2489. is_fetched = is_to_attr_fetched(instance.__class__, to_attr)
  2490. # For singly related objects, we have to avoid getting the attribute
  2491. # from the object, as this will trigger the query. So we first try
  2492. # on the class, in order to get the descriptor object.
  2493. rel_obj_descriptor = getattr(instance.__class__, through_attr, None)
  2494. if rel_obj_descriptor is None:
  2495. attr_found = hasattr(instance, through_attr)
  2496. else:
  2497. attr_found = True
  2498. if rel_obj_descriptor:
  2499. # singly related object, descriptor object has the
  2500. # get_prefetch_querysets() method.
  2501. if hasattr(rel_obj_descriptor, "get_prefetch_querysets"):
  2502. prefetcher = rel_obj_descriptor
  2503. # If to_attr is set, check if the value has already been set,
  2504. # which is done with has_to_attr_attribute(). Do not use the
  2505. # method from the descriptor, as the cache_name it defines
  2506. # checks the field name, not the to_attr value.
  2507. if through_attr == to_attr:
  2508. is_fetched = rel_obj_descriptor.is_cached
  2509. else:
  2510. # descriptor doesn't support prefetching, so we go ahead and
  2511. # get the attribute on the instance rather than the class to
  2512. # support many related managers
  2513. rel_obj = getattr(instance, through_attr)
  2514. if hasattr(rel_obj, "get_prefetch_querysets"):
  2515. prefetcher = rel_obj
  2516. if through_attr == to_attr:
  2517. def in_prefetched_cache(instance):
  2518. return through_attr in instance._prefetched_objects_cache
  2519. is_fetched = in_prefetched_cache
  2520. return prefetcher, rel_obj_descriptor, attr_found, is_fetched
  2521. def prefetch_one_level(instances, prefetcher, lookup, level):
  2522. """
  2523. Helper function for prefetch_related_objects().
  2524. Run prefetches on all instances using the prefetcher object,
  2525. assigning results to relevant caches in instance.
  2526. Return the prefetched objects along with any additional prefetches that
  2527. must be done due to prefetch_related lookups found from default managers.
  2528. """
  2529. # prefetcher must have a method get_prefetch_querysets() which takes a list
  2530. # of instances, and returns a tuple:
  2531. # (queryset of instances of self.model that are related to passed in
  2532. # instances,
  2533. # callable that gets value to be matched for returned instances,
  2534. # callable that gets value to be matched for passed in instances,
  2535. # boolean that is True for singly related objects,
  2536. # cache or field name to assign to,
  2537. # boolean that is True when the previous argument is a cache name vs a
  2538. # field name).
  2539. # The 'values to be matched' must be hashable as they will be used
  2540. # in a dictionary.
  2541. (
  2542. rel_qs,
  2543. rel_obj_attr,
  2544. instance_attr,
  2545. single,
  2546. cache_name,
  2547. is_descriptor,
  2548. ) = prefetcher.get_prefetch_querysets(
  2549. instances, lookup.get_current_querysets(level)
  2550. )
  2551. # We have to handle the possibility that the QuerySet we just got back
  2552. # contains some prefetch_related lookups. We don't want to trigger the
  2553. # prefetch_related functionality by evaluating the query. Rather, we need
  2554. # to merge in the prefetch_related lookups.
  2555. # Copy the lookups in case it is a Prefetch object which could be reused
  2556. # later (happens in nested prefetch_related).
  2557. additional_lookups = [
  2558. copy.copy(additional_lookup)
  2559. for additional_lookup in getattr(rel_qs, "_prefetch_related_lookups", ())
  2560. ]
  2561. if additional_lookups:
  2562. # Don't need to clone because the manager should have given us a fresh
  2563. # instance, so we access an internal instead of using public interface
  2564. # for performance reasons.
  2565. rel_qs._prefetch_related_lookups = ()
  2566. all_related_objects = list(rel_qs)
  2567. rel_obj_cache = {}
  2568. for rel_obj in all_related_objects:
  2569. rel_attr_val = rel_obj_attr(rel_obj)
  2570. rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj)
  2571. to_attr, as_attr = lookup.get_current_to_attr(level)
  2572. # Make sure `to_attr` does not conflict with a field.
  2573. if as_attr and instances:
  2574. # We assume that objects retrieved are homogeneous (which is the
  2575. # premise of prefetch_related), so what applies to first object applies
  2576. # to all.
  2577. model = instances[0].__class__
  2578. try:
  2579. model._meta.get_field(to_attr)
  2580. except exceptions.FieldDoesNotExist:
  2581. pass
  2582. else:
  2583. msg = "to_attr={} conflicts with a field on the {} model."
  2584. raise ValueError(msg.format(to_attr, model.__name__))
  2585. # Whether or not we're prefetching the last part of the lookup.
  2586. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level
  2587. for obj in instances:
  2588. instance_attr_val = instance_attr(obj)
  2589. vals = rel_obj_cache.get(instance_attr_val, [])
  2590. if single:
  2591. val = vals[0] if vals else None
  2592. if as_attr:
  2593. # A to_attr has been given for the prefetch.
  2594. setattr(obj, to_attr, val)
  2595. elif is_descriptor:
  2596. # cache_name points to a field name in obj.
  2597. # This field is a descriptor for a related object.
  2598. setattr(obj, cache_name, val)
  2599. else:
  2600. # No to_attr has been given for this prefetch operation and the
  2601. # cache_name does not point to a descriptor. Store the value of
  2602. # the field in the object's field cache.
  2603. obj._state.fields_cache[cache_name] = val
  2604. else:
  2605. if as_attr:
  2606. setattr(obj, to_attr, vals)
  2607. else:
  2608. manager = getattr(obj, to_attr)
  2609. if leaf and lookup.queryset is not None:
  2610. qs = manager._apply_rel_filters(lookup.queryset._chain())
  2611. else:
  2612. qs = manager.get_queryset()
  2613. qs._result_cache = vals
  2614. # We don't want the individual qs doing prefetch_related now,
  2615. # since we have merged this into the current work.
  2616. qs._prefetch_done = True
  2617. obj._prefetched_objects_cache[cache_name] = qs
  2618. return all_related_objects, additional_lookups
  2619. class RelatedPopulator:
  2620. """
  2621. RelatedPopulator is used for select_related() object instantiation.
  2622. The idea is that each select_related() model will be populated by a
  2623. different RelatedPopulator instance. The RelatedPopulator instances get
  2624. klass_info and select (computed in SQLCompiler) plus the used db as
  2625. input for initialization. That data is used to compute which columns
  2626. to use, how to instantiate the model, and how to populate the links
  2627. between the objects.
  2628. The actual creation of the objects is done in populate() method. This
  2629. method gets row and from_obj as input and populates the select_related()
  2630. model instance.
  2631. """
  2632. def __init__(self, klass_info, select, db, fetch_mode):
  2633. self.db = db
  2634. self.fetch_mode = fetch_mode
  2635. # Pre-compute needed attributes. The attributes are:
  2636. # - model_cls: the possibly deferred model class to instantiate
  2637. # - either:
  2638. # - cols_start, cols_end: usually the columns in the row are
  2639. # in the same order model_cls.__init__ expects them, so we
  2640. # can instantiate by model_cls(*row[cols_start:cols_end])
  2641. # - reorder_for_init: When select_related descends to a child
  2642. # class, then we want to reuse the already selected parent
  2643. # data. However, in this case the parent data isn't necessarily
  2644. # in the same order that Model.__init__ expects it to be, so
  2645. # we have to reorder the parent data. The reorder_for_init
  2646. # attribute contains a function used to reorder the field data
  2647. # in the order __init__ expects it.
  2648. # - pk_idx: the index of the primary key field in the reordered
  2649. # model data. Used to check if a related object exists at all.
  2650. # - init_list: the field attnames fetched from the database. For
  2651. # deferred models this isn't the same as all attnames of the
  2652. # model's fields.
  2653. # - related_populators: a list of RelatedPopulator instances if
  2654. # select_related() descends to related models from this model.
  2655. # - local_setter, remote_setter: Methods to set cached values on
  2656. # the object being populated and on the remote object. Usually
  2657. # these are Field.set_cached_value() methods.
  2658. select_fields = klass_info["select_fields"]
  2659. from_parent = klass_info["from_parent"]
  2660. if not from_parent:
  2661. self.cols_start = select_fields[0]
  2662. self.cols_end = select_fields[-1] + 1
  2663. self.init_list = [
  2664. f[0].target.attname for f in select[self.cols_start : self.cols_end]
  2665. ]
  2666. self.reorder_for_init = None
  2667. else:
  2668. attname_indexes = {
  2669. select[idx][0].target.attname: idx for idx in select_fields
  2670. }
  2671. model_init_attnames = (
  2672. f.attname for f in klass_info["model"]._meta.concrete_fields
  2673. )
  2674. self.init_list = [
  2675. attname for attname in model_init_attnames if attname in attname_indexes
  2676. ]
  2677. self.reorder_for_init = operator.itemgetter(
  2678. *[attname_indexes[attname] for attname in self.init_list]
  2679. )
  2680. self.model_cls = klass_info["model"]
  2681. # A primary key must have all of its constituents not-NULL as
  2682. # NULL != NULL and thus NULL cannot be referenced through a foreign
  2683. # relationship. Therefore checking for a single member of the primary
  2684. # key is enough to determine if the referenced object exists or not.
  2685. self.pk_idx = self.init_list.index(self.model_cls._meta.pk_fields[0].attname)
  2686. self.related_populators = get_related_populators(
  2687. klass_info, select, self.db, fetch_mode
  2688. )
  2689. self.local_setter = klass_info["local_setter"]
  2690. self.remote_setter = klass_info["remote_setter"]
  2691. def populate(self, row, from_obj):
  2692. if self.reorder_for_init:
  2693. obj_data = self.reorder_for_init(row)
  2694. else:
  2695. obj_data = row[self.cols_start : self.cols_end]
  2696. if obj_data[self.pk_idx] is None:
  2697. obj = None
  2698. else:
  2699. obj = self.model_cls.from_db(
  2700. self.db,
  2701. self.init_list,
  2702. obj_data,
  2703. fetch_mode=self.fetch_mode,
  2704. )
  2705. for rel_iter in self.related_populators:
  2706. rel_iter.populate(row, obj)
  2707. self.local_setter(from_obj, obj)
  2708. if obj is not None:
  2709. self.remote_setter(obj, from_obj)
  2710. def get_related_populators(klass_info, select, db, fetch_mode):
  2711. iterators = []
  2712. related_klass_infos = klass_info.get("related_klass_infos", [])
  2713. for rel_klass_info in related_klass_infos:
  2714. rel_cls = RelatedPopulator(rel_klass_info, select, db, fetch_mode)
  2715. iterators.append(rel_cls)
  2716. return iterators