query.py 103 KB

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