query.py 100 KB

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