Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.py 98KB

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