query.py 100 KB

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