You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.py 78KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  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 collections import OrderedDict, namedtuple
  8. from functools import lru_cache
  9. from itertools import chain
  10. from django.conf import settings
  11. from django.core import exceptions
  12. from django.db import (
  13. DJANGO_VERSION_PICKLE_KEY, IntegrityError, connections, router,
  14. transaction,
  15. )
  16. from django.db.models import DateField, DateTimeField, sql
  17. from django.db.models.constants import LOOKUP_SEP
  18. from django.db.models.deletion import Collector
  19. from django.db.models.expressions import Case, Expression, F, Value, When
  20. from django.db.models.fields import AutoField
  21. from django.db.models.functions import Cast, Trunc
  22. from django.db.models.query_utils import FilteredRelation, InvalidQuery, Q
  23. from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE
  24. from django.db.utils import NotSupportedError
  25. from django.utils import timezone
  26. from django.utils.deprecation import RemovedInDjango30Warning
  27. from django.utils.functional import cached_property, partition
  28. from django.utils.version import get_version
  29. # The maximum number of items to display in a QuerySet.__repr__
  30. REPR_OUTPUT_SIZE = 20
  31. # Pull into this namespace for backwards compatibility.
  32. EmptyResultSet = sql.EmptyResultSet
  33. class BaseIterable:
  34. def __init__(self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE):
  35. self.queryset = queryset
  36. self.chunked_fetch = chunked_fetch
  37. self.chunk_size = chunk_size
  38. class ModelIterable(BaseIterable):
  39. """Iterable that yields a model instance for each row."""
  40. def __iter__(self):
  41. queryset = self.queryset
  42. db = queryset.db
  43. compiler = queryset.query.get_compiler(using=db)
  44. # Execute the query. This will also fill compiler.select, klass_info,
  45. # and annotations.
  46. results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  47. select, klass_info, annotation_col_map = (compiler.select, compiler.klass_info,
  48. compiler.annotation_col_map)
  49. model_cls = klass_info['model']
  50. select_fields = klass_info['select_fields']
  51. model_fields_start, model_fields_end = select_fields[0], select_fields[-1] + 1
  52. init_list = [f[0].target.attname
  53. for f in select[model_fields_start:model_fields_end]]
  54. related_populators = get_related_populators(klass_info, select, db)
  55. known_related_objects = [
  56. (field, related_objs, operator.attrgetter(*[
  57. field.attname
  58. if from_field == 'self' else
  59. queryset.model._meta.get_field(from_field).attname
  60. for from_field in field.from_fields
  61. ])) for field, related_objs in queryset._known_related_objects.items()
  62. ]
  63. for row in compiler.results_iter(results):
  64. obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end])
  65. for rel_populator in related_populators:
  66. rel_populator.populate(row, obj)
  67. if annotation_col_map:
  68. for attr_name, col_pos in annotation_col_map.items():
  69. setattr(obj, attr_name, row[col_pos])
  70. # Add the known related objects to the model.
  71. for field, rel_objs, rel_getter in known_related_objects:
  72. # Avoid overwriting objects loaded by, e.g., select_related().
  73. if field.is_cached(obj):
  74. continue
  75. rel_obj_id = rel_getter(obj)
  76. try:
  77. rel_obj = rel_objs[rel_obj_id]
  78. except KeyError:
  79. pass # May happen in qs1 | qs2 scenarios.
  80. else:
  81. setattr(obj, field.name, rel_obj)
  82. yield obj
  83. class ValuesIterable(BaseIterable):
  84. """
  85. Iterable returned by QuerySet.values() that yields a dict for each row.
  86. """
  87. def __iter__(self):
  88. queryset = self.queryset
  89. query = queryset.query
  90. compiler = query.get_compiler(queryset.db)
  91. # extra(select=...) cols are always at the start of the row.
  92. names = [
  93. *query.extra_select,
  94. *query.values_select,
  95. *query.annotation_select,
  96. ]
  97. indexes = range(len(names))
  98. for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size):
  99. yield {names[i]: row[i] for i in indexes}
  100. class ValuesListIterable(BaseIterable):
  101. """
  102. Iterable returned by QuerySet.values_list(flat=False) that yields a tuple
  103. for each row.
  104. """
  105. def __iter__(self):
  106. queryset = self.queryset
  107. query = queryset.query
  108. compiler = query.get_compiler(queryset.db)
  109. if queryset._fields:
  110. # extra(select=...) cols are always at the start of the row.
  111. names = [
  112. *query.extra_select,
  113. *query.values_select,
  114. *query.annotation_select,
  115. ]
  116. fields = [*queryset._fields, *(f for f in query.annotation_select if f not in queryset._fields)]
  117. if fields != names:
  118. # Reorder according to fields.
  119. index_map = {name: idx for idx, name in enumerate(names)}
  120. rowfactory = operator.itemgetter(*[index_map[f] for f in fields])
  121. return map(
  122. rowfactory,
  123. compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  124. )
  125. return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  126. class NamedValuesListIterable(ValuesListIterable):
  127. """
  128. Iterable returned by QuerySet.values_list(named=True) that yields a
  129. namedtuple for each row.
  130. """
  131. @staticmethod
  132. @lru_cache()
  133. def create_namedtuple_class(*names):
  134. # Cache namedtuple() with @lru_cache() since it's too slow to be
  135. # called for every QuerySet evaluation.
  136. return namedtuple('Row', names)
  137. def __iter__(self):
  138. queryset = self.queryset
  139. if queryset._fields:
  140. names = queryset._fields
  141. else:
  142. query = queryset.query
  143. names = [*query.extra_select, *query.values_select, *query.annotation_select]
  144. tuple_class = self.create_namedtuple_class(*names)
  145. new = tuple.__new__
  146. for row in super().__iter__():
  147. yield new(tuple_class, row)
  148. class FlatValuesListIterable(BaseIterable):
  149. """
  150. Iterable returned by QuerySet.values_list(flat=True) that yields single
  151. values.
  152. """
  153. def __iter__(self):
  154. queryset = self.queryset
  155. compiler = queryset.query.get_compiler(queryset.db)
  156. for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size):
  157. yield row[0]
  158. class QuerySet:
  159. """Represent a lazy database lookup for a set of objects."""
  160. def __init__(self, model=None, query=None, using=None, hints=None):
  161. self.model = model
  162. self._db = using
  163. self._hints = hints or {}
  164. self.query = query or sql.Query(self.model)
  165. self._result_cache = None
  166. self._sticky_filter = False
  167. self._for_write = False
  168. self._prefetch_related_lookups = ()
  169. self._prefetch_done = False
  170. self._known_related_objects = {} # {rel_field: {pk: rel_obj}}
  171. self._iterable_class = ModelIterable
  172. self._fields = None
  173. def as_manager(cls):
  174. # Address the circular dependency between `Queryset` and `Manager`.
  175. from django.db.models.manager import Manager
  176. manager = Manager.from_queryset(cls)()
  177. manager._built_with_as_manager = True
  178. return manager
  179. as_manager.queryset_only = True
  180. as_manager = classmethod(as_manager)
  181. ########################
  182. # PYTHON MAGIC METHODS #
  183. ########################
  184. def __deepcopy__(self, memo):
  185. """Don't populate the QuerySet's cache."""
  186. obj = self.__class__()
  187. for k, v in self.__dict__.items():
  188. if k == '_result_cache':
  189. obj.__dict__[k] = None
  190. else:
  191. obj.__dict__[k] = copy.deepcopy(v, memo)
  192. return obj
  193. def __getstate__(self):
  194. # Force the cache to be fully populated.
  195. self._fetch_all()
  196. return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: get_version()}
  197. def __setstate__(self, state):
  198. msg = None
  199. pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
  200. if pickled_version:
  201. current_version = get_version()
  202. if current_version != pickled_version:
  203. msg = (
  204. "Pickled queryset instance's Django version %s does not "
  205. "match the current version %s." % (pickled_version, current_version)
  206. )
  207. else:
  208. msg = "Pickled queryset instance's Django version is not specified."
  209. if msg:
  210. warnings.warn(msg, RuntimeWarning, stacklevel=2)
  211. self.__dict__.update(state)
  212. def __repr__(self):
  213. data = list(self[:REPR_OUTPUT_SIZE + 1])
  214. if len(data) > REPR_OUTPUT_SIZE:
  215. data[-1] = "...(remaining elements truncated)..."
  216. return '<%s %r>' % (self.__class__.__name__, data)
  217. def __len__(self):
  218. self._fetch_all()
  219. return len(self._result_cache)
  220. def __iter__(self):
  221. """
  222. The queryset iterator protocol uses three nested iterators in the
  223. default case:
  224. 1. sql.compiler.execute_sql()
  225. - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)
  226. using cursor.fetchmany(). This part is responsible for
  227. doing some column masking, and returning the rows in chunks.
  228. 2. sql.compiler.results_iter()
  229. - Returns one row at time. At this point the rows are still just
  230. tuples. In some cases the return values are converted to
  231. Python values at this location.
  232. 3. self.iterator()
  233. - Responsible for turning the rows into model objects.
  234. """
  235. self._fetch_all()
  236. return iter(self._result_cache)
  237. def __bool__(self):
  238. self._fetch_all()
  239. return bool(self._result_cache)
  240. def __getitem__(self, k):
  241. """Retrieve an item or slice from the set of results."""
  242. if not isinstance(k, (int, slice)):
  243. raise TypeError
  244. assert ((not isinstance(k, slice) and (k >= 0)) or
  245. (isinstance(k, slice) and (k.start is None or k.start >= 0) and
  246. (k.stop is None or k.stop >= 0))), \
  247. "Negative indexing is not supported."
  248. if self._result_cache is not None:
  249. return self._result_cache[k]
  250. if isinstance(k, slice):
  251. qs = self._chain()
  252. if k.start is not None:
  253. start = int(k.start)
  254. else:
  255. start = None
  256. if k.stop is not None:
  257. stop = int(k.stop)
  258. else:
  259. stop = None
  260. qs.query.set_limits(start, stop)
  261. return list(qs)[::k.step] if k.step else qs
  262. qs = self._chain()
  263. qs.query.set_limits(k, k + 1)
  264. qs._fetch_all()
  265. return qs._result_cache[0]
  266. def __and__(self, other):
  267. self._merge_sanity_check(other)
  268. if isinstance(other, EmptyQuerySet):
  269. return other
  270. if isinstance(self, EmptyQuerySet):
  271. return self
  272. combined = self._chain()
  273. combined._merge_known_related_objects(other)
  274. combined.query.combine(other.query, sql.AND)
  275. return combined
  276. def __or__(self, other):
  277. self._merge_sanity_check(other)
  278. if isinstance(self, EmptyQuerySet):
  279. return other
  280. if isinstance(other, EmptyQuerySet):
  281. return self
  282. query = self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values('pk'))
  283. combined = query._chain()
  284. combined._merge_known_related_objects(other)
  285. if not other.query.can_filter():
  286. other = other.model._base_manager.filter(pk__in=other.values('pk'))
  287. combined.query.combine(other.query, sql.OR)
  288. return combined
  289. ####################################
  290. # METHODS THAT DO DATABASE QUERIES #
  291. ####################################
  292. def _iterator(self, use_chunked_fetch, chunk_size):
  293. yield from self._iterable_class(self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size)
  294. def iterator(self, chunk_size=2000):
  295. """
  296. An iterator over the results from applying this QuerySet to the
  297. database.
  298. """
  299. if chunk_size <= 0:
  300. raise ValueError('Chunk size must be strictly positive.')
  301. use_chunked_fetch = not connections[self.db].settings_dict.get('DISABLE_SERVER_SIDE_CURSORS')
  302. return self._iterator(use_chunked_fetch, chunk_size)
  303. def aggregate(self, *args, **kwargs):
  304. """
  305. Return a dictionary containing the calculations (aggregation)
  306. over the current queryset.
  307. If args is present the expression is passed as a kwarg using
  308. the Aggregate object's default alias.
  309. """
  310. if self.query.distinct_fields:
  311. raise NotImplementedError("aggregate() + distinct(fields) not implemented.")
  312. self._validate_values_are_expressions((*args, *kwargs.values()), method_name='aggregate')
  313. for arg in args:
  314. # The default_alias property raises TypeError if default_alias
  315. # can't be set automatically or AttributeError if it isn't an
  316. # attribute.
  317. try:
  318. arg.default_alias
  319. except (AttributeError, TypeError):
  320. raise TypeError("Complex aggregates require an alias")
  321. kwargs[arg.default_alias] = arg
  322. query = self.query.chain()
  323. for (alias, aggregate_expr) in kwargs.items():
  324. query.add_annotation(aggregate_expr, alias, is_summary=True)
  325. if not query.annotations[alias].contains_aggregate:
  326. raise TypeError("%s is not an aggregate expression" % alias)
  327. return query.get_aggregation(self.db, kwargs)
  328. def count(self):
  329. """
  330. Perform a SELECT COUNT() and return the number of records as an
  331. integer.
  332. If the QuerySet is already fully cached, return the length of the
  333. cached results set to avoid multiple SELECT COUNT(*) calls.
  334. """
  335. if self._result_cache is not None:
  336. return len(self._result_cache)
  337. return self.query.get_count(using=self.db)
  338. def get(self, *args, **kwargs):
  339. """
  340. Perform the query and return a single object matching the given
  341. keyword arguments.
  342. """
  343. clone = self.filter(*args, **kwargs)
  344. if self.query.can_filter() and not self.query.distinct_fields:
  345. clone = clone.order_by()
  346. num = len(clone)
  347. if num == 1:
  348. return clone._result_cache[0]
  349. if not num:
  350. raise self.model.DoesNotExist(
  351. "%s matching query does not exist." %
  352. self.model._meta.object_name
  353. )
  354. raise self.model.MultipleObjectsReturned(
  355. "get() returned more than one %s -- it returned %s!" %
  356. (self.model._meta.object_name, num)
  357. )
  358. def create(self, **kwargs):
  359. """
  360. Create a new object with the given kwargs, saving it to the database
  361. and returning the created object.
  362. """
  363. obj = self.model(**kwargs)
  364. self._for_write = True
  365. obj.save(force_insert=True, using=self.db)
  366. return obj
  367. def _populate_pk_values(self, objs):
  368. for obj in objs:
  369. if obj.pk is None:
  370. obj.pk = obj._meta.pk.get_pk_value_on_save(obj)
  371. def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
  372. """
  373. Insert each of the instances into the database. Do *not* call
  374. save() on each of the instances, do not send any pre/post_save
  375. signals, and do not set the primary key attribute if it is an
  376. autoincrement field (except if features.can_return_ids_from_bulk_insert=True).
  377. Multi-table models are not supported.
  378. """
  379. # When you bulk insert you don't get the primary keys back (if it's an
  380. # autoincrement, except if can_return_ids_from_bulk_insert=True), so
  381. # you can't insert into the child tables which references this. There
  382. # are two workarounds:
  383. # 1) This could be implemented if you didn't have an autoincrement pk
  384. # 2) You could do it by doing O(n) normal inserts into the parent
  385. # tables to get the primary keys back and then doing a single bulk
  386. # insert into the childmost table.
  387. # We currently set the primary keys on the objects when using
  388. # PostgreSQL via the RETURNING ID clause. It should be possible for
  389. # Oracle as well, but the semantics for extracting the primary keys is
  390. # trickier so it's not done yet.
  391. assert batch_size is None or batch_size > 0
  392. # Check that the parents share the same concrete model with the our
  393. # model to detect the inheritance pattern ConcreteGrandParent ->
  394. # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy
  395. # would not identify that case as involving multiple tables.
  396. for parent in self.model._meta.get_parent_list():
  397. if parent._meta.concrete_model is not self.model._meta.concrete_model:
  398. raise ValueError("Can't bulk create a multi-table inherited model")
  399. if not objs:
  400. return objs
  401. self._for_write = True
  402. connection = connections[self.db]
  403. fields = self.model._meta.concrete_fields
  404. objs = list(objs)
  405. self._populate_pk_values(objs)
  406. with transaction.atomic(using=self.db, savepoint=False):
  407. objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs)
  408. if objs_with_pk:
  409. self._batched_insert(objs_with_pk, fields, batch_size, ignore_conflicts=ignore_conflicts)
  410. for obj_with_pk in objs_with_pk:
  411. obj_with_pk._state.adding = False
  412. obj_with_pk._state.db = self.db
  413. if objs_without_pk:
  414. fields = [f for f in fields if not isinstance(f, AutoField)]
  415. ids = self._batched_insert(objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts)
  416. if connection.features.can_return_ids_from_bulk_insert and not ignore_conflicts:
  417. assert len(ids) == len(objs_without_pk)
  418. for obj_without_pk, pk in zip(objs_without_pk, ids):
  419. obj_without_pk.pk = pk
  420. obj_without_pk._state.adding = False
  421. obj_without_pk._state.db = self.db
  422. return objs
  423. def bulk_update(self, objs, fields, batch_size=None):
  424. """
  425. Update the given fields in each of the given objects in the database.
  426. """
  427. if batch_size is not None and batch_size < 0:
  428. raise ValueError('Batch size must be a positive integer.')
  429. if not fields:
  430. raise ValueError('Field names must be given to bulk_update().')
  431. objs = tuple(objs)
  432. if any(obj.pk is None for obj in objs):
  433. raise ValueError('All bulk_update() objects must have a primary key set.')
  434. fields = [self.model._meta.get_field(name) for name in fields]
  435. if any(not f.concrete or f.many_to_many for f in fields):
  436. raise ValueError('bulk_update() can only be used with concrete fields.')
  437. if any(f.primary_key for f in fields):
  438. raise ValueError('bulk_update() cannot be used with primary key fields.')
  439. if not objs:
  440. return
  441. # PK is used twice in the resulting update query, once in the filter
  442. # and once in the WHEN. Each field will also have one CAST.
  443. max_batch_size = connections[self.db].ops.bulk_batch_size(['pk', 'pk'] + fields, objs)
  444. batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size
  445. requires_casting = connections[self.db].features.requires_casted_case_in_updates
  446. batches = (objs[i:i + batch_size] for i in range(0, len(objs), batch_size))
  447. updates = []
  448. for batch_objs in batches:
  449. update_kwargs = {}
  450. for field in fields:
  451. when_statements = []
  452. for obj in batch_objs:
  453. attr = getattr(obj, field.attname)
  454. if not isinstance(attr, Expression):
  455. attr = Value(attr, output_field=field)
  456. when_statements.append(When(pk=obj.pk, then=attr))
  457. case_statement = Case(*when_statements, output_field=field)
  458. if requires_casting:
  459. case_statement = Cast(case_statement, output_field=field)
  460. update_kwargs[field.attname] = case_statement
  461. updates.append(([obj.pk for obj in batch_objs], update_kwargs))
  462. with transaction.atomic(using=self.db, savepoint=False):
  463. for pks, update_kwargs in updates:
  464. self.filter(pk__in=pks).update(**update_kwargs)
  465. bulk_update.alters_data = True
  466. def get_or_create(self, defaults=None, **kwargs):
  467. """
  468. Look up an object with the given kwargs, creating one if necessary.
  469. Return a tuple of (object, created), where created is a boolean
  470. specifying whether an object was created.
  471. """
  472. # The get() needs to be targeted at the write database in order
  473. # to avoid potential transaction consistency problems.
  474. self._for_write = True
  475. try:
  476. return self.get(**kwargs), False
  477. except self.model.DoesNotExist:
  478. params = self._extract_model_params(defaults, **kwargs)
  479. return self._create_object_from_params(kwargs, params)
  480. def update_or_create(self, defaults=None, **kwargs):
  481. """
  482. Look up an object with the given kwargs, updating one with defaults
  483. if it exists, otherwise create a new one.
  484. Return a tuple (object, created), where created is a boolean
  485. specifying whether an object was created.
  486. """
  487. defaults = defaults or {}
  488. self._for_write = True
  489. with transaction.atomic(using=self.db):
  490. try:
  491. obj = self.select_for_update().get(**kwargs)
  492. except self.model.DoesNotExist:
  493. params = self._extract_model_params(defaults, **kwargs)
  494. # Lock the row so that a concurrent update is blocked until
  495. # after update_or_create() has performed its save.
  496. obj, created = self._create_object_from_params(kwargs, params, lock=True)
  497. if created:
  498. return obj, created
  499. for k, v in defaults.items():
  500. setattr(obj, k, v() if callable(v) else v)
  501. obj.save(using=self.db)
  502. return obj, False
  503. def _create_object_from_params(self, lookup, params, lock=False):
  504. """
  505. Try to create an object using passed params. Used by get_or_create()
  506. and update_or_create().
  507. """
  508. try:
  509. with transaction.atomic(using=self.db):
  510. params = {k: v() if callable(v) else v for k, v in params.items()}
  511. obj = self.create(**params)
  512. return obj, True
  513. except IntegrityError as e:
  514. try:
  515. qs = self.select_for_update() if lock else self
  516. return qs.get(**lookup), False
  517. except self.model.DoesNotExist:
  518. pass
  519. raise e
  520. def _extract_model_params(self, defaults, **kwargs):
  521. """
  522. Prepare `params` for creating a model instance based on the given
  523. kwargs; for use by get_or_create() and update_or_create().
  524. """
  525. defaults = defaults or {}
  526. params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}
  527. params.update(defaults)
  528. property_names = self.model._meta._property_names
  529. invalid_params = []
  530. for param in params:
  531. try:
  532. self.model._meta.get_field(param)
  533. except exceptions.FieldDoesNotExist:
  534. # It's okay to use a model's property if it has a setter.
  535. if not (param in property_names and getattr(self.model, param).fset):
  536. invalid_params.append(param)
  537. if invalid_params:
  538. raise exceptions.FieldError(
  539. "Invalid field name(s) for model %s: '%s'." % (
  540. self.model._meta.object_name,
  541. "', '".join(sorted(invalid_params)),
  542. ))
  543. return params
  544. def _earliest(self, *fields, field_name=None):
  545. """
  546. Return the earliest object according to fields (if given) or by the
  547. model's Meta.get_latest_by.
  548. """
  549. if fields and field_name is not None:
  550. raise ValueError('Cannot use both positional arguments and the field_name keyword argument.')
  551. if field_name is not None:
  552. warnings.warn(
  553. 'The field_name keyword argument to earliest() and latest() '
  554. 'is deprecated in favor of passing positional arguments.',
  555. RemovedInDjango30Warning,
  556. )
  557. order_by = (field_name,)
  558. elif fields:
  559. order_by = fields
  560. else:
  561. order_by = getattr(self.model._meta, 'get_latest_by')
  562. if order_by and not isinstance(order_by, (tuple, list)):
  563. order_by = (order_by,)
  564. if order_by is None:
  565. raise ValueError(
  566. "earliest() and latest() require either fields as positional "
  567. "arguments or 'get_latest_by' in the model's Meta."
  568. )
  569. assert self.query.can_filter(), \
  570. "Cannot change a query once a slice has been taken."
  571. obj = self._chain()
  572. obj.query.set_limits(high=1)
  573. obj.query.clear_ordering(force_empty=True)
  574. obj.query.add_ordering(*order_by)
  575. return obj.get()
  576. def earliest(self, *fields, field_name=None):
  577. return self._earliest(*fields, field_name=field_name)
  578. def latest(self, *fields, field_name=None):
  579. return self.reverse()._earliest(*fields, field_name=field_name)
  580. def first(self):
  581. """Return the first object of a query or None if no match is found."""
  582. for obj in (self if self.ordered else self.order_by('pk'))[:1]:
  583. return obj
  584. def last(self):
  585. """Return the last object of a query or None if no match is found."""
  586. for obj in (self.reverse() if self.ordered else self.order_by('-pk'))[:1]:
  587. return obj
  588. def in_bulk(self, id_list=None, *, field_name='pk'):
  589. """
  590. Return a dictionary mapping each of the given IDs to the object with
  591. that ID. If `id_list` isn't provided, evaluate the entire QuerySet.
  592. """
  593. assert self.query.can_filter(), \
  594. "Cannot use 'limit' or 'offset' with in_bulk"
  595. if field_name != 'pk' and not self.model._meta.get_field(field_name).unique:
  596. raise ValueError("in_bulk()'s field_name must be a unique field but %r isn't." % field_name)
  597. if id_list is not None:
  598. if not id_list:
  599. return {}
  600. filter_key = '{}__in'.format(field_name)
  601. batch_size = connections[self.db].features.max_query_params
  602. id_list = tuple(id_list)
  603. # If the database has a limit on the number of query parameters
  604. # (e.g. SQLite), retrieve objects in batches if necessary.
  605. if batch_size and batch_size < len(id_list):
  606. qs = ()
  607. for offset in range(0, len(id_list), batch_size):
  608. batch = id_list[offset:offset + batch_size]
  609. qs += tuple(self.filter(**{filter_key: batch}).order_by())
  610. else:
  611. qs = self.filter(**{filter_key: id_list}).order_by()
  612. else:
  613. qs = self._chain()
  614. return {getattr(obj, field_name): obj for obj in qs}
  615. def delete(self):
  616. """Delete the records in the current QuerySet."""
  617. assert self.query.can_filter(), \
  618. "Cannot use 'limit' or 'offset' with delete."
  619. if self._fields is not None:
  620. raise TypeError("Cannot call delete() after .values() or .values_list()")
  621. del_query = self._chain()
  622. # The delete is actually 2 queries - one to find related objects,
  623. # and one to delete. Make sure that the discovery of related
  624. # objects is performed on the same database as the deletion.
  625. del_query._for_write = True
  626. # Disable non-supported fields.
  627. del_query.query.select_for_update = False
  628. del_query.query.select_related = False
  629. del_query.query.clear_ordering(force_empty=True)
  630. collector = Collector(using=del_query.db)
  631. collector.collect(del_query)
  632. deleted, _rows_count = collector.delete()
  633. # Clear the result cache, in case this QuerySet gets reused.
  634. self._result_cache = None
  635. return deleted, _rows_count
  636. delete.alters_data = True
  637. delete.queryset_only = True
  638. def _raw_delete(self, using):
  639. """
  640. Delete objects found from the given queryset in single direct SQL
  641. query. No signals are sent and there is no protection for cascades.
  642. """
  643. return sql.DeleteQuery(self.model).delete_qs(self, using)
  644. _raw_delete.alters_data = True
  645. def update(self, **kwargs):
  646. """
  647. Update all elements in the current QuerySet, setting all the given
  648. fields to the appropriate values.
  649. """
  650. assert self.query.can_filter(), \
  651. "Cannot update a query once a slice has been taken."
  652. self._for_write = True
  653. query = self.query.chain(sql.UpdateQuery)
  654. query.add_update_values(kwargs)
  655. # Clear any annotations so that they won't be present in subqueries.
  656. query._annotations = None
  657. with transaction.mark_for_rollback_on_error(using=self.db):
  658. rows = query.get_compiler(self.db).execute_sql(CURSOR)
  659. self._result_cache = None
  660. return rows
  661. update.alters_data = True
  662. def _update(self, values):
  663. """
  664. A version of update() that accepts field objects instead of field names.
  665. Used primarily for model saving and not intended for use by general
  666. code (it requires too much poking around at model internals to be
  667. useful at that level).
  668. """
  669. assert self.query.can_filter(), \
  670. "Cannot update a query once a slice has been taken."
  671. query = self.query.chain(sql.UpdateQuery)
  672. query.add_update_fields(values)
  673. # Clear any annotations so that they won't be present in subqueries.
  674. query._annotations = None
  675. self._result_cache = None
  676. return query.get_compiler(self.db).execute_sql(CURSOR)
  677. _update.alters_data = True
  678. _update.queryset_only = False
  679. def exists(self):
  680. if self._result_cache is None:
  681. return self.query.has_results(using=self.db)
  682. return bool(self._result_cache)
  683. def _prefetch_related_objects(self):
  684. # This method can only be called once the result cache has been filled.
  685. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)
  686. self._prefetch_done = True
  687. def explain(self, *, format=None, **options):
  688. return self.query.explain(using=self.db, format=format, **options)
  689. ##################################################
  690. # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
  691. ##################################################
  692. def raw(self, raw_query, params=None, translations=None, using=None):
  693. if using is None:
  694. using = self.db
  695. qs = RawQuerySet(raw_query, model=self.model, params=params, translations=translations, using=using)
  696. qs._prefetch_related_lookups = self._prefetch_related_lookups[:]
  697. return qs
  698. def _values(self, *fields, **expressions):
  699. clone = self._chain()
  700. if expressions:
  701. clone = clone.annotate(**expressions)
  702. clone._fields = fields
  703. clone.query.set_values(fields)
  704. return clone
  705. def values(self, *fields, **expressions):
  706. fields += tuple(expressions)
  707. clone = self._values(*fields, **expressions)
  708. clone._iterable_class = ValuesIterable
  709. return clone
  710. def values_list(self, *fields, flat=False, named=False):
  711. if flat and named:
  712. raise TypeError("'flat' and 'named' can't be used together.")
  713. if flat and len(fields) > 1:
  714. raise TypeError("'flat' is not valid when values_list is called with more than one field.")
  715. field_names = {f for f in fields if not hasattr(f, 'resolve_expression')}
  716. _fields = []
  717. expressions = {}
  718. counter = 1
  719. for field in fields:
  720. if hasattr(field, 'resolve_expression'):
  721. field_id_prefix = getattr(field, 'default_alias', field.__class__.__name__.lower())
  722. while True:
  723. field_id = field_id_prefix + str(counter)
  724. counter += 1
  725. if field_id not in field_names:
  726. break
  727. expressions[field_id] = field
  728. _fields.append(field_id)
  729. else:
  730. _fields.append(field)
  731. clone = self._values(*_fields, **expressions)
  732. clone._iterable_class = (
  733. NamedValuesListIterable if named
  734. else FlatValuesListIterable if flat
  735. else ValuesListIterable
  736. )
  737. return clone
  738. def dates(self, field_name, kind, order='ASC'):
  739. """
  740. Return a list of date objects representing all available dates for
  741. the given field_name, scoped to 'kind'.
  742. """
  743. assert kind in ('year', 'month', 'week', 'day'), \
  744. "'kind' must be one of 'year', 'month', 'week', or 'day'."
  745. assert order in ('ASC', 'DESC'), \
  746. "'order' must be either 'ASC' or 'DESC'."
  747. return self.annotate(
  748. datefield=Trunc(field_name, kind, output_field=DateField()),
  749. plain_field=F(field_name)
  750. ).values_list(
  751. 'datefield', flat=True
  752. ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datefield')
  753. def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
  754. """
  755. Return a list of datetime objects representing all available
  756. datetimes for the given field_name, scoped to 'kind'.
  757. """
  758. assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \
  759. "'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'."
  760. assert order in ('ASC', 'DESC'), \
  761. "'order' must be either 'ASC' or 'DESC'."
  762. if settings.USE_TZ:
  763. if tzinfo is None:
  764. tzinfo = timezone.get_current_timezone()
  765. else:
  766. tzinfo = None
  767. return self.annotate(
  768. datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
  769. plain_field=F(field_name)
  770. ).values_list(
  771. 'datetimefield', flat=True
  772. ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
  773. def none(self):
  774. """Return an empty QuerySet."""
  775. clone = self._chain()
  776. clone.query.set_empty()
  777. return clone
  778. ##################################################################
  779. # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
  780. ##################################################################
  781. def all(self):
  782. """
  783. Return a new QuerySet that is a copy of the current one. This allows a
  784. QuerySet to proxy for a model manager in some cases.
  785. """
  786. return self._chain()
  787. def filter(self, *args, **kwargs):
  788. """
  789. Return a new QuerySet instance with the args ANDed to the existing
  790. set.
  791. """
  792. return self._filter_or_exclude(False, *args, **kwargs)
  793. def exclude(self, *args, **kwargs):
  794. """
  795. Return a new QuerySet instance with NOT (args) ANDed to the existing
  796. set.
  797. """
  798. return self._filter_or_exclude(True, *args, **kwargs)
  799. def _filter_or_exclude(self, negate, *args, **kwargs):
  800. if args or kwargs:
  801. assert self.query.can_filter(), \
  802. "Cannot filter a query once a slice has been taken."
  803. clone = self._chain()
  804. if negate:
  805. clone.query.add_q(~Q(*args, **kwargs))
  806. else:
  807. clone.query.add_q(Q(*args, **kwargs))
  808. return clone
  809. def complex_filter(self, filter_obj):
  810. """
  811. Return a new QuerySet instance with filter_obj added to the filters.
  812. filter_obj can be a Q object or a dictionary of keyword lookup
  813. arguments.
  814. This exists to support framework features such as 'limit_choices_to',
  815. and usually it will be more natural to use other methods.
  816. """
  817. if isinstance(filter_obj, Q):
  818. clone = self._chain()
  819. clone.query.add_q(filter_obj)
  820. return clone
  821. else:
  822. return self._filter_or_exclude(None, **filter_obj)
  823. def _combinator_query(self, combinator, *other_qs, all=False):
  824. # Clone the query to inherit the select list and everything
  825. clone = self._chain()
  826. # Clear limits and ordering so they can be reapplied
  827. clone.query.clear_ordering(True)
  828. clone.query.clear_limits()
  829. clone.query.combined_queries = (self.query,) + tuple(qs.query for qs in other_qs)
  830. clone.query.combinator = combinator
  831. clone.query.combinator_all = all
  832. return clone
  833. def union(self, *other_qs, all=False):
  834. # If the query is an EmptyQuerySet, combine all nonempty querysets.
  835. if isinstance(self, EmptyQuerySet):
  836. qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)]
  837. return qs[0]._combinator_query('union', *qs[1:], all=all) if qs else self
  838. return self._combinator_query('union', *other_qs, all=all)
  839. def intersection(self, *other_qs):
  840. # If any query is an EmptyQuerySet, return it.
  841. if isinstance(self, EmptyQuerySet):
  842. return self
  843. for other in other_qs:
  844. if isinstance(other, EmptyQuerySet):
  845. return other
  846. return self._combinator_query('intersection', *other_qs)
  847. def difference(self, *other_qs):
  848. # If the query is an EmptyQuerySet, return it.
  849. if isinstance(self, EmptyQuerySet):
  850. return self
  851. return self._combinator_query('difference', *other_qs)
  852. def select_for_update(self, nowait=False, skip_locked=False, of=()):
  853. """
  854. Return a new QuerySet instance that will select objects with a
  855. FOR UPDATE lock.
  856. """
  857. if nowait and skip_locked:
  858. raise ValueError('The nowait option cannot be used with skip_locked.')
  859. obj = self._chain()
  860. obj._for_write = True
  861. obj.query.select_for_update = True
  862. obj.query.select_for_update_nowait = nowait
  863. obj.query.select_for_update_skip_locked = skip_locked
  864. obj.query.select_for_update_of = of
  865. return obj
  866. def select_related(self, *fields):
  867. """
  868. Return a new QuerySet instance that will select related objects.
  869. If fields are specified, they must be ForeignKey fields and only those
  870. related objects are included in the selection.
  871. If select_related(None) is called, clear the list.
  872. """
  873. if self._fields is not None:
  874. raise TypeError("Cannot call select_related() after .values() or .values_list()")
  875. obj = self._chain()
  876. if fields == (None,):
  877. obj.query.select_related = False
  878. elif fields:
  879. obj.query.add_select_related(fields)
  880. else:
  881. obj.query.select_related = True
  882. return obj
  883. def prefetch_related(self, *lookups):
  884. """
  885. Return a new QuerySet instance that will prefetch the specified
  886. Many-To-One and Many-To-Many related objects when the QuerySet is
  887. evaluated.
  888. When prefetch_related() is called more than once, append to the list of
  889. prefetch lookups. If prefetch_related(None) is called, clear the list.
  890. """
  891. clone = self._chain()
  892. if lookups == (None,):
  893. clone._prefetch_related_lookups = ()
  894. else:
  895. for lookup in lookups:
  896. if isinstance(lookup, Prefetch):
  897. lookup = lookup.prefetch_to
  898. lookup = lookup.split(LOOKUP_SEP, 1)[0]
  899. if lookup in self.query._filtered_relations:
  900. raise ValueError('prefetch_related() is not supported with FilteredRelation.')
  901. clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups
  902. return clone
  903. def annotate(self, *args, **kwargs):
  904. """
  905. Return a query set in which the returned objects have been annotated
  906. with extra data or aggregations.
  907. """
  908. self._validate_values_are_expressions(args + tuple(kwargs.values()), method_name='annotate')
  909. annotations = OrderedDict() # To preserve ordering of args
  910. for arg in args:
  911. # The default_alias property may raise a TypeError.
  912. try:
  913. if arg.default_alias in kwargs:
  914. raise ValueError("The named annotation '%s' conflicts with the "
  915. "default name for another annotation."
  916. % arg.default_alias)
  917. except TypeError:
  918. raise TypeError("Complex annotations require an alias")
  919. annotations[arg.default_alias] = arg
  920. annotations.update(kwargs)
  921. clone = self._chain()
  922. names = self._fields
  923. if names is None:
  924. names = set(chain.from_iterable(
  925. (field.name, field.attname) if hasattr(field, 'attname') else (field.name,)
  926. for field in self.model._meta.get_fields()
  927. ))
  928. for alias, annotation in annotations.items():
  929. if alias in names:
  930. raise ValueError("The annotation '%s' conflicts with a field on "
  931. "the model." % alias)
  932. if isinstance(annotation, FilteredRelation):
  933. clone.query.add_filtered_relation(annotation, alias)
  934. else:
  935. clone.query.add_annotation(annotation, alias, is_summary=False)
  936. for alias, annotation in clone.query.annotations.items():
  937. if alias in annotations and annotation.contains_aggregate:
  938. if clone._fields is None:
  939. clone.query.group_by = True
  940. else:
  941. clone.query.set_group_by()
  942. break
  943. return clone
  944. def order_by(self, *field_names):
  945. """Return a new QuerySet instance with the ordering changed."""
  946. assert self.query.can_filter(), \
  947. "Cannot reorder a query once a slice has been taken."
  948. obj = self._chain()
  949. obj.query.clear_ordering(force_empty=False)
  950. obj.query.add_ordering(*field_names)
  951. return obj
  952. def distinct(self, *field_names):
  953. """
  954. Return a new QuerySet instance that will select only distinct results.
  955. """
  956. assert self.query.can_filter(), \
  957. "Cannot create distinct fields once a slice has been taken."
  958. obj = self._chain()
  959. obj.query.add_distinct_fields(*field_names)
  960. return obj
  961. def extra(self, select=None, where=None, params=None, tables=None,
  962. order_by=None, select_params=None):
  963. """Add extra SQL fragments to the query."""
  964. assert self.query.can_filter(), \
  965. "Cannot change a query once a slice has been taken"
  966. clone = self._chain()
  967. clone.query.add_extra(select, select_params, where, params, tables, order_by)
  968. return clone
  969. def reverse(self):
  970. """Reverse the ordering of the QuerySet."""
  971. if not self.query.can_filter():
  972. raise TypeError('Cannot reverse a query once a slice has been taken.')
  973. clone = self._chain()
  974. clone.query.standard_ordering = not clone.query.standard_ordering
  975. return clone
  976. def defer(self, *fields):
  977. """
  978. Defer the loading of data for certain fields until they are accessed.
  979. Add the set of deferred fields to any existing set of deferred fields.
  980. The only exception to this is if None is passed in as the only
  981. parameter, in which case removal all deferrals.
  982. """
  983. if self._fields is not None:
  984. raise TypeError("Cannot call defer() after .values() or .values_list()")
  985. clone = self._chain()
  986. if fields == (None,):
  987. clone.query.clear_deferred_loading()
  988. else:
  989. clone.query.add_deferred_loading(fields)
  990. return clone
  991. def only(self, *fields):
  992. """
  993. Essentially, the opposite of defer(). Only the fields passed into this
  994. method and that are not already specified as deferred are loaded
  995. immediately when the queryset is evaluated.
  996. """
  997. if self._fields is not None:
  998. raise TypeError("Cannot call only() after .values() or .values_list()")
  999. if fields == (None,):
  1000. # Can only pass None to defer(), not only(), as the rest option.
  1001. # That won't stop people trying to do this, so let's be explicit.
  1002. raise TypeError("Cannot pass None as an argument to only().")
  1003. for field in fields:
  1004. field = field.split(LOOKUP_SEP, 1)[0]
  1005. if field in self.query._filtered_relations:
  1006. raise ValueError('only() is not supported with FilteredRelation.')
  1007. clone = self._chain()
  1008. clone.query.add_immediate_loading(fields)
  1009. return clone
  1010. def using(self, alias):
  1011. """Select which database this QuerySet should execute against."""
  1012. clone = self._chain()
  1013. clone._db = alias
  1014. return clone
  1015. ###################################
  1016. # PUBLIC INTROSPECTION ATTRIBUTES #
  1017. ###################################
  1018. @property
  1019. def ordered(self):
  1020. """
  1021. Return True if the QuerySet is ordered -- i.e. has an order_by()
  1022. clause or a default ordering on the model (or is empty).
  1023. """
  1024. if isinstance(self, EmptyQuerySet):
  1025. return True
  1026. if self.query.extra_order_by or self.query.order_by:
  1027. return True
  1028. elif self.query.default_ordering and self.query.get_meta().ordering:
  1029. return True
  1030. else:
  1031. return False
  1032. @property
  1033. def db(self):
  1034. """Return the database used if this query is executed now."""
  1035. if self._for_write:
  1036. return self._db or router.db_for_write(self.model, **self._hints)
  1037. return self._db or router.db_for_read(self.model, **self._hints)
  1038. ###################
  1039. # PRIVATE METHODS #
  1040. ###################
  1041. def _insert(self, objs, fields, return_id=False, raw=False, using=None, ignore_conflicts=False):
  1042. """
  1043. Insert a new record for the given model. This provides an interface to
  1044. the InsertQuery class and is how Model.save() is implemented.
  1045. """
  1046. self._for_write = True
  1047. if using is None:
  1048. using = self.db
  1049. query = sql.InsertQuery(self.model, ignore_conflicts=ignore_conflicts)
  1050. query.insert_values(fields, objs, raw=raw)
  1051. return query.get_compiler(using=using).execute_sql(return_id)
  1052. _insert.alters_data = True
  1053. _insert.queryset_only = False
  1054. def _batched_insert(self, objs, fields, batch_size, ignore_conflicts=False):
  1055. """
  1056. Helper method for bulk_create() to insert objs one batch at a time.
  1057. """
  1058. if ignore_conflicts and not connections[self.db].features.supports_ignore_conflicts:
  1059. raise NotSupportedError('This database backend does not support ignoring conflicts.')
  1060. ops = connections[self.db].ops
  1061. batch_size = (batch_size or max(ops.bulk_batch_size(fields, objs), 1))
  1062. inserted_ids = []
  1063. bulk_return = connections[self.db].features.can_return_ids_from_bulk_insert
  1064. for item in [objs[i:i + batch_size] for i in range(0, len(objs), batch_size)]:
  1065. if bulk_return and not ignore_conflicts:
  1066. inserted_id = self._insert(
  1067. item, fields=fields, using=self.db, return_id=True,
  1068. ignore_conflicts=ignore_conflicts,
  1069. )
  1070. if isinstance(inserted_id, list):
  1071. inserted_ids.extend(inserted_id)
  1072. else:
  1073. inserted_ids.append(inserted_id)
  1074. else:
  1075. self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
  1076. return inserted_ids
  1077. def _chain(self, **kwargs):
  1078. """
  1079. Return a copy of the current QuerySet that's ready for another
  1080. operation.
  1081. """
  1082. obj = self._clone()
  1083. if obj._sticky_filter:
  1084. obj.query.filter_is_sticky = True
  1085. obj._sticky_filter = False
  1086. obj.__dict__.update(kwargs)
  1087. return obj
  1088. def _clone(self):
  1089. """
  1090. Return a copy of the current QuerySet. A lightweight alternative
  1091. to deepcopy().
  1092. """
  1093. c = self.__class__(model=self.model, query=self.query.chain(), using=self._db, hints=self._hints)
  1094. c._sticky_filter = self._sticky_filter
  1095. c._for_write = self._for_write
  1096. c._prefetch_related_lookups = self._prefetch_related_lookups[:]
  1097. c._known_related_objects = self._known_related_objects
  1098. c._iterable_class = self._iterable_class
  1099. c._fields = self._fields
  1100. return c
  1101. def _fetch_all(self):
  1102. if self._result_cache is None:
  1103. self._result_cache = list(self._iterable_class(self))
  1104. if self._prefetch_related_lookups and not self._prefetch_done:
  1105. self._prefetch_related_objects()
  1106. def _next_is_sticky(self):
  1107. """
  1108. Indicate that the next filter call and the one following that should
  1109. be treated as a single filter. This is only important when it comes to
  1110. determining when to reuse tables for many-to-many filters. Required so
  1111. that we can filter naturally on the results of related managers.
  1112. This doesn't return a clone of the current QuerySet (it returns
  1113. "self"). The method is only used internally and should be immediately
  1114. followed by a filter() that does create a clone.
  1115. """
  1116. self._sticky_filter = True
  1117. return self
  1118. def _merge_sanity_check(self, other):
  1119. """Check that two QuerySet classes may be merged."""
  1120. if self._fields is not None and (
  1121. set(self.query.values_select) != set(other.query.values_select) or
  1122. set(self.query.extra_select) != set(other.query.extra_select) or
  1123. set(self.query.annotation_select) != set(other.query.annotation_select)):
  1124. raise TypeError(
  1125. "Merging '%s' classes must involve the same values in each case."
  1126. % self.__class__.__name__
  1127. )
  1128. def _merge_known_related_objects(self, other):
  1129. """
  1130. Keep track of all known related objects from either QuerySet instance.
  1131. """
  1132. for field, objects in other._known_related_objects.items():
  1133. self._known_related_objects.setdefault(field, {}).update(objects)
  1134. def resolve_expression(self, *args, **kwargs):
  1135. if self._fields and len(self._fields) > 1:
  1136. # values() queryset can only be used as nested queries
  1137. # if they are set up to select only a single field.
  1138. raise TypeError('Cannot use multi-field values as a filter value.')
  1139. query = self.query.resolve_expression(*args, **kwargs)
  1140. query._db = self._db
  1141. return query
  1142. resolve_expression.queryset_only = True
  1143. def _add_hints(self, **hints):
  1144. """
  1145. Update hinting information for use by routers. Add new key/values or
  1146. overwrite existing key/values.
  1147. """
  1148. self._hints.update(hints)
  1149. def _has_filters(self):
  1150. """
  1151. Check if this QuerySet has any filtering going on. This isn't
  1152. equivalent with checking if all objects are present in results, for
  1153. example, qs[1:]._has_filters() -> False.
  1154. """
  1155. return self.query.has_filters()
  1156. @staticmethod
  1157. def _validate_values_are_expressions(values, method_name):
  1158. invalid_args = sorted(str(arg) for arg in values if not hasattr(arg, 'resolve_expression'))
  1159. if invalid_args:
  1160. raise TypeError(
  1161. 'QuerySet.%s() received non-expression(s): %s.' % (
  1162. method_name,
  1163. ', '.join(invalid_args),
  1164. )
  1165. )
  1166. class InstanceCheckMeta(type):
  1167. def __instancecheck__(self, instance):
  1168. return isinstance(instance, QuerySet) and instance.query.is_empty()
  1169. class EmptyQuerySet(metaclass=InstanceCheckMeta):
  1170. """
  1171. Marker class to checking if a queryset is empty by .none():
  1172. isinstance(qs.none(), EmptyQuerySet) -> True
  1173. """
  1174. def __init__(self, *args, **kwargs):
  1175. raise TypeError("EmptyQuerySet can't be instantiated")
  1176. class RawQuerySet:
  1177. """
  1178. Provide an iterator which converts the results of raw SQL queries into
  1179. annotated model instances.
  1180. """
  1181. def __init__(self, raw_query, model=None, query=None, params=None,
  1182. translations=None, using=None, hints=None):
  1183. self.raw_query = raw_query
  1184. self.model = model
  1185. self._db = using
  1186. self._hints = hints or {}
  1187. self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params)
  1188. self.params = params or ()
  1189. self.translations = translations or {}
  1190. self._result_cache = None
  1191. self._prefetch_related_lookups = ()
  1192. self._prefetch_done = False
  1193. def resolve_model_init_order(self):
  1194. """Resolve the init field names and value positions."""
  1195. converter = connections[self.db].introspection.identifier_converter
  1196. model_init_fields = [f for f in self.model._meta.fields if converter(f.column) in self.columns]
  1197. annotation_fields = [(column, pos) for pos, column in enumerate(self.columns)
  1198. if column not in self.model_fields]
  1199. model_init_order = [self.columns.index(converter(f.column)) for f in model_init_fields]
  1200. model_init_names = [f.attname for f in model_init_fields]
  1201. return model_init_names, model_init_order, annotation_fields
  1202. def prefetch_related(self, *lookups):
  1203. """Same as QuerySet.prefetch_related()"""
  1204. clone = self._clone()
  1205. if lookups == (None,):
  1206. clone._prefetch_related_lookups = ()
  1207. else:
  1208. clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups
  1209. return clone
  1210. def _prefetch_related_objects(self):
  1211. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups)
  1212. self._prefetch_done = True
  1213. def _clone(self):
  1214. """Same as QuerySet._clone()"""
  1215. c = self.__class__(
  1216. self.raw_query, model=self.model, query=self.query, params=self.params,
  1217. translations=self.translations, using=self._db, hints=self._hints
  1218. )
  1219. c._prefetch_related_lookups = self._prefetch_related_lookups[:]
  1220. return c
  1221. def _fetch_all(self):
  1222. if self._result_cache is None:
  1223. self._result_cache = list(self.iterator())
  1224. if self._prefetch_related_lookups and not self._prefetch_done:
  1225. self._prefetch_related_objects()
  1226. def __len__(self):
  1227. self._fetch_all()
  1228. return len(self._result_cache)
  1229. def __bool__(self):
  1230. self._fetch_all()
  1231. return bool(self._result_cache)
  1232. def __iter__(self):
  1233. self._fetch_all()
  1234. return iter(self._result_cache)
  1235. def iterator(self):
  1236. # Cache some things for performance reasons outside the loop.
  1237. db = self.db
  1238. compiler = connections[db].ops.compiler('SQLCompiler')(
  1239. self.query, connections[db], db
  1240. )
  1241. query = iter(self.query)
  1242. try:
  1243. model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order()
  1244. if self.model._meta.pk.attname not in model_init_names:
  1245. raise InvalidQuery('Raw query must include the primary key')
  1246. model_cls = self.model
  1247. fields = [self.model_fields.get(c) for c in self.columns]
  1248. converters = compiler.get_converters([
  1249. f.get_col(f.model._meta.db_table) if f else None for f in fields
  1250. ])
  1251. if converters:
  1252. query = compiler.apply_converters(query, converters)
  1253. for values in query:
  1254. # Associate fields to values
  1255. model_init_values = [values[pos] for pos in model_init_pos]
  1256. instance = model_cls.from_db(db, model_init_names, model_init_values)
  1257. if annotation_fields:
  1258. for column, pos in annotation_fields:
  1259. setattr(instance, column, values[pos])
  1260. yield instance
  1261. finally:
  1262. # Done iterating the Query. If it has its own cursor, close it.
  1263. if hasattr(self.query, 'cursor') and self.query.cursor:
  1264. self.query.cursor.close()
  1265. def __repr__(self):
  1266. return "<%s: %s>" % (self.__class__.__name__, self.query)
  1267. def __getitem__(self, k):
  1268. return list(self)[k]
  1269. @property
  1270. def db(self):
  1271. """Return the database used if this query is executed now."""
  1272. return self._db or router.db_for_read(self.model, **self._hints)
  1273. def using(self, alias):
  1274. """Select the database this RawQuerySet should execute against."""
  1275. return RawQuerySet(
  1276. self.raw_query, model=self.model,
  1277. query=self.query.chain(using=alias),
  1278. params=self.params, translations=self.translations,
  1279. using=alias,
  1280. )
  1281. @cached_property
  1282. def columns(self):
  1283. """
  1284. A list of model field names in the order they'll appear in the
  1285. query results.
  1286. """
  1287. columns = self.query.get_columns()
  1288. # Adjust any column names which don't match field names
  1289. for (query_name, model_name) in self.translations.items():
  1290. # Ignore translations for nonexistent column names
  1291. try:
  1292. index = columns.index(query_name)
  1293. except ValueError:
  1294. pass
  1295. else:
  1296. columns[index] = model_name
  1297. return columns
  1298. @cached_property
  1299. def model_fields(self):
  1300. """A dict mapping column names to model field names."""
  1301. converter = connections[self.db].introspection.identifier_converter
  1302. model_fields = {}
  1303. for field in self.model._meta.fields:
  1304. name, column = field.get_attname_column()
  1305. model_fields[converter(column)] = field
  1306. return model_fields
  1307. class Prefetch:
  1308. def __init__(self, lookup, queryset=None, to_attr=None):
  1309. # `prefetch_through` is the path we traverse to perform the prefetch.
  1310. self.prefetch_through = lookup
  1311. # `prefetch_to` is the path to the attribute that stores the result.
  1312. self.prefetch_to = lookup
  1313. if queryset is not None and not issubclass(queryset._iterable_class, ModelIterable):
  1314. raise ValueError('Prefetch querysets cannot use values().')
  1315. if to_attr:
  1316. self.prefetch_to = LOOKUP_SEP.join(lookup.split(LOOKUP_SEP)[:-1] + [to_attr])
  1317. self.queryset = queryset
  1318. self.to_attr = to_attr
  1319. def __getstate__(self):
  1320. obj_dict = self.__dict__.copy()
  1321. if self.queryset is not None:
  1322. # Prevent the QuerySet from being evaluated
  1323. obj_dict['queryset'] = self.queryset._chain(
  1324. _result_cache=[],
  1325. _prefetch_done=True,
  1326. )
  1327. return obj_dict
  1328. def add_prefix(self, prefix):
  1329. self.prefetch_through = prefix + LOOKUP_SEP + self.prefetch_through
  1330. self.prefetch_to = prefix + LOOKUP_SEP + self.prefetch_to
  1331. def get_current_prefetch_to(self, level):
  1332. return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[:level + 1])
  1333. def get_current_to_attr(self, level):
  1334. parts = self.prefetch_to.split(LOOKUP_SEP)
  1335. to_attr = parts[level]
  1336. as_attr = self.to_attr and level == len(parts) - 1
  1337. return to_attr, as_attr
  1338. def get_current_queryset(self, level):
  1339. if self.get_current_prefetch_to(level) == self.prefetch_to:
  1340. return self.queryset
  1341. return None
  1342. def __eq__(self, other):
  1343. return isinstance(other, Prefetch) and self.prefetch_to == other.prefetch_to
  1344. def __hash__(self):
  1345. return hash((self.__class__, self.prefetch_to))
  1346. def normalize_prefetch_lookups(lookups, prefix=None):
  1347. """Normalize lookups into Prefetch objects."""
  1348. ret = []
  1349. for lookup in lookups:
  1350. if not isinstance(lookup, Prefetch):
  1351. lookup = Prefetch(lookup)
  1352. if prefix:
  1353. lookup.add_prefix(prefix)
  1354. ret.append(lookup)
  1355. return ret
  1356. def prefetch_related_objects(model_instances, *related_lookups):
  1357. """
  1358. Populate prefetched object caches for a list of model instances based on
  1359. the lookups/Prefetch instances given.
  1360. """
  1361. if not model_instances:
  1362. return # nothing to do
  1363. # We need to be able to dynamically add to the list of prefetch_related
  1364. # lookups that we look up (see below). So we need some book keeping to
  1365. # ensure we don't do duplicate work.
  1366. done_queries = {} # dictionary of things like 'foo__bar': [results]
  1367. auto_lookups = set() # we add to this as we go through.
  1368. followed_descriptors = set() # recursion protection
  1369. all_lookups = normalize_prefetch_lookups(reversed(related_lookups))
  1370. while all_lookups:
  1371. lookup = all_lookups.pop()
  1372. if lookup.prefetch_to in done_queries:
  1373. if lookup.queryset:
  1374. raise ValueError("'%s' lookup was already seen with a different queryset. "
  1375. "You may need to adjust the ordering of your lookups." % lookup.prefetch_to)
  1376. continue
  1377. # Top level, the list of objects to decorate is the result cache
  1378. # from the primary QuerySet. It won't be for deeper levels.
  1379. obj_list = model_instances
  1380. through_attrs = lookup.prefetch_through.split(LOOKUP_SEP)
  1381. for level, through_attr in enumerate(through_attrs):
  1382. # Prepare main instances
  1383. if not obj_list:
  1384. break
  1385. prefetch_to = lookup.get_current_prefetch_to(level)
  1386. if prefetch_to in done_queries:
  1387. # Skip any prefetching, and any object preparation
  1388. obj_list = done_queries[prefetch_to]
  1389. continue
  1390. # Prepare objects:
  1391. good_objects = True
  1392. for obj in obj_list:
  1393. # Since prefetching can re-use instances, it is possible to have
  1394. # the same instance multiple times in obj_list, so obj might
  1395. # already be prepared.
  1396. if not hasattr(obj, '_prefetched_objects_cache'):
  1397. try:
  1398. obj._prefetched_objects_cache = {}
  1399. except (AttributeError, TypeError):
  1400. # Must be an immutable object from
  1401. # values_list(flat=True), for example (TypeError) or
  1402. # a QuerySet subclass that isn't returning Model
  1403. # instances (AttributeError), either in Django or a 3rd
  1404. # party. prefetch_related() doesn't make sense, so quit.
  1405. good_objects = False
  1406. break
  1407. if not good_objects:
  1408. break
  1409. # Descend down tree
  1410. # We assume that objects retrieved are homogeneous (which is the premise
  1411. # of prefetch_related), so what applies to first object applies to all.
  1412. first_obj = obj_list[0]
  1413. to_attr = lookup.get_current_to_attr(level)[0]
  1414. prefetcher, descriptor, attr_found, is_fetched = get_prefetcher(first_obj, through_attr, to_attr)
  1415. if not attr_found:
  1416. raise AttributeError("Cannot find '%s' on %s object, '%s' is an invalid "
  1417. "parameter to prefetch_related()" %
  1418. (through_attr, first_obj.__class__.__name__, lookup.prefetch_through))
  1419. if level == len(through_attrs) - 1 and prefetcher is None:
  1420. # Last one, this *must* resolve to something that supports
  1421. # prefetching, otherwise there is no point adding it and the
  1422. # developer asking for it has made a mistake.
  1423. raise ValueError("'%s' does not resolve to an item that supports "
  1424. "prefetching - this is an invalid parameter to "
  1425. "prefetch_related()." % lookup.prefetch_through)
  1426. if prefetcher is not None and not is_fetched:
  1427. obj_list, additional_lookups = prefetch_one_level(obj_list, prefetcher, lookup, level)
  1428. # We need to ensure we don't keep adding lookups from the
  1429. # same relationships to stop infinite recursion. So, if we
  1430. # are already on an automatically added lookup, don't add
  1431. # the new lookups from relationships we've seen already.
  1432. if not (prefetch_to in done_queries and lookup in auto_lookups and descriptor in followed_descriptors):
  1433. done_queries[prefetch_to] = obj_list
  1434. new_lookups = normalize_prefetch_lookups(reversed(additional_lookups), prefetch_to)
  1435. auto_lookups.update(new_lookups)
  1436. all_lookups.extend(new_lookups)
  1437. followed_descriptors.add(descriptor)
  1438. else:
  1439. # Either a singly related object that has already been fetched
  1440. # (e.g. via select_related), or hopefully some other property
  1441. # that doesn't support prefetching but needs to be traversed.
  1442. # We replace the current list of parent objects with the list
  1443. # of related objects, filtering out empty or missing values so
  1444. # that we can continue with nullable or reverse relations.
  1445. new_obj_list = []
  1446. for obj in obj_list:
  1447. if through_attr in getattr(obj, '_prefetched_objects_cache', ()):
  1448. # If related objects have been prefetched, use the
  1449. # cache rather than the object's through_attr.
  1450. new_obj = list(obj._prefetched_objects_cache.get(through_attr))
  1451. else:
  1452. try:
  1453. new_obj = getattr(obj, through_attr)
  1454. except exceptions.ObjectDoesNotExist:
  1455. continue
  1456. if new_obj is None:
  1457. continue
  1458. # We special-case `list` rather than something more generic
  1459. # like `Iterable` because we don't want to accidentally match
  1460. # user models that define __iter__.
  1461. if isinstance(new_obj, list):
  1462. new_obj_list.extend(new_obj)
  1463. else:
  1464. new_obj_list.append(new_obj)
  1465. obj_list = new_obj_list
  1466. def get_prefetcher(instance, through_attr, to_attr):
  1467. """
  1468. For the attribute 'through_attr' on the given instance, find
  1469. an object that has a get_prefetch_queryset().
  1470. Return a 4 tuple containing:
  1471. (the object with get_prefetch_queryset (or None),
  1472. the descriptor object representing this relationship (or None),
  1473. a boolean that is False if the attribute was not found at all,
  1474. a boolean that is True if the attribute has already been fetched)
  1475. """
  1476. prefetcher = None
  1477. is_fetched = False
  1478. # For singly related objects, we have to avoid getting the attribute
  1479. # from the object, as this will trigger the query. So we first try
  1480. # on the class, in order to get the descriptor object.
  1481. rel_obj_descriptor = getattr(instance.__class__, through_attr, None)
  1482. if rel_obj_descriptor is None:
  1483. attr_found = hasattr(instance, through_attr)
  1484. else:
  1485. attr_found = True
  1486. if rel_obj_descriptor:
  1487. # singly related object, descriptor object has the
  1488. # get_prefetch_queryset() method.
  1489. if hasattr(rel_obj_descriptor, 'get_prefetch_queryset'):
  1490. prefetcher = rel_obj_descriptor
  1491. if rel_obj_descriptor.is_cached(instance):
  1492. is_fetched = True
  1493. else:
  1494. # descriptor doesn't support prefetching, so we go ahead and get
  1495. # the attribute on the instance rather than the class to
  1496. # support many related managers
  1497. rel_obj = getattr(instance, through_attr)
  1498. if hasattr(rel_obj, 'get_prefetch_queryset'):
  1499. prefetcher = rel_obj
  1500. if through_attr != to_attr:
  1501. # Special case cached_property instances because hasattr
  1502. # triggers attribute computation and assignment.
  1503. if isinstance(getattr(instance.__class__, to_attr, None), cached_property):
  1504. is_fetched = to_attr in instance.__dict__
  1505. else:
  1506. is_fetched = hasattr(instance, to_attr)
  1507. else:
  1508. is_fetched = through_attr in instance._prefetched_objects_cache
  1509. return prefetcher, rel_obj_descriptor, attr_found, is_fetched
  1510. def prefetch_one_level(instances, prefetcher, lookup, level):
  1511. """
  1512. Helper function for prefetch_related_objects().
  1513. Run prefetches on all instances using the prefetcher object,
  1514. assigning results to relevant caches in instance.
  1515. Return the prefetched objects along with any additional prefetches that
  1516. must be done due to prefetch_related lookups found from default managers.
  1517. """
  1518. # prefetcher must have a method get_prefetch_queryset() which takes a list
  1519. # of instances, and returns a tuple:
  1520. # (queryset of instances of self.model that are related to passed in instances,
  1521. # callable that gets value to be matched for returned instances,
  1522. # callable that gets value to be matched for passed in instances,
  1523. # boolean that is True for singly related objects,
  1524. # cache or field name to assign to,
  1525. # boolean that is True when the previous argument is a cache name vs a field name).
  1526. # The 'values to be matched' must be hashable as they will be used
  1527. # in a dictionary.
  1528. rel_qs, rel_obj_attr, instance_attr, single, cache_name, is_descriptor = (
  1529. prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level)))
  1530. # We have to handle the possibility that the QuerySet we just got back
  1531. # contains some prefetch_related lookups. We don't want to trigger the
  1532. # prefetch_related functionality by evaluating the query. Rather, we need
  1533. # to merge in the prefetch_related lookups.
  1534. # Copy the lookups in case it is a Prefetch object which could be reused
  1535. # later (happens in nested prefetch_related).
  1536. additional_lookups = [
  1537. copy.copy(additional_lookup) for additional_lookup
  1538. in getattr(rel_qs, '_prefetch_related_lookups', ())
  1539. ]
  1540. if additional_lookups:
  1541. # Don't need to clone because the manager should have given us a fresh
  1542. # instance, so we access an internal instead of using public interface
  1543. # for performance reasons.
  1544. rel_qs._prefetch_related_lookups = ()
  1545. all_related_objects = list(rel_qs)
  1546. rel_obj_cache = {}
  1547. for rel_obj in all_related_objects:
  1548. rel_attr_val = rel_obj_attr(rel_obj)
  1549. rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj)
  1550. to_attr, as_attr = lookup.get_current_to_attr(level)
  1551. # Make sure `to_attr` does not conflict with a field.
  1552. if as_attr and instances:
  1553. # We assume that objects retrieved are homogeneous (which is the premise
  1554. # of prefetch_related), so what applies to first object applies to all.
  1555. model = instances[0].__class__
  1556. try:
  1557. model._meta.get_field(to_attr)
  1558. except exceptions.FieldDoesNotExist:
  1559. pass
  1560. else:
  1561. msg = 'to_attr={} conflicts with a field on the {} model.'
  1562. raise ValueError(msg.format(to_attr, model.__name__))
  1563. # Whether or not we're prefetching the last part of the lookup.
  1564. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level
  1565. for obj in instances:
  1566. instance_attr_val = instance_attr(obj)
  1567. vals = rel_obj_cache.get(instance_attr_val, [])
  1568. if single:
  1569. val = vals[0] if vals else None
  1570. if as_attr:
  1571. # A to_attr has been given for the prefetch.
  1572. setattr(obj, to_attr, val)
  1573. elif is_descriptor:
  1574. # cache_name points to a field name in obj.
  1575. # This field is a descriptor for a related object.
  1576. setattr(obj, cache_name, val)
  1577. else:
  1578. # No to_attr has been given for this prefetch operation and the
  1579. # cache_name does not point to a descriptor. Store the value of
  1580. # the field in the object's field cache.
  1581. obj._state.fields_cache[cache_name] = val
  1582. else:
  1583. if as_attr:
  1584. setattr(obj, to_attr, vals)
  1585. else:
  1586. manager = getattr(obj, to_attr)
  1587. if leaf and lookup.queryset is not None:
  1588. qs = manager._apply_rel_filters(lookup.queryset)
  1589. else:
  1590. qs = manager.get_queryset()
  1591. qs._result_cache = vals
  1592. # We don't want the individual qs doing prefetch_related now,
  1593. # since we have merged this into the current work.
  1594. qs._prefetch_done = True
  1595. obj._prefetched_objects_cache[cache_name] = qs
  1596. return all_related_objects, additional_lookups
  1597. class RelatedPopulator:
  1598. """
  1599. RelatedPopulator is used for select_related() object instantiation.
  1600. The idea is that each select_related() model will be populated by a
  1601. different RelatedPopulator instance. The RelatedPopulator instances get
  1602. klass_info and select (computed in SQLCompiler) plus the used db as
  1603. input for initialization. That data is used to compute which columns
  1604. to use, how to instantiate the model, and how to populate the links
  1605. between the objects.
  1606. The actual creation of the objects is done in populate() method. This
  1607. method gets row and from_obj as input and populates the select_related()
  1608. model instance.
  1609. """
  1610. def __init__(self, klass_info, select, db):
  1611. self.db = db
  1612. # Pre-compute needed attributes. The attributes are:
  1613. # - model_cls: the possibly deferred model class to instantiate
  1614. # - either:
  1615. # - cols_start, cols_end: usually the columns in the row are
  1616. # in the same order model_cls.__init__ expects them, so we
  1617. # can instantiate by model_cls(*row[cols_start:cols_end])
  1618. # - reorder_for_init: When select_related descends to a child
  1619. # class, then we want to reuse the already selected parent
  1620. # data. However, in this case the parent data isn't necessarily
  1621. # in the same order that Model.__init__ expects it to be, so
  1622. # we have to reorder the parent data. The reorder_for_init
  1623. # attribute contains a function used to reorder the field data
  1624. # in the order __init__ expects it.
  1625. # - pk_idx: the index of the primary key field in the reordered
  1626. # model data. Used to check if a related object exists at all.
  1627. # - init_list: the field attnames fetched from the database. For
  1628. # deferred models this isn't the same as all attnames of the
  1629. # model's fields.
  1630. # - related_populators: a list of RelatedPopulator instances if
  1631. # select_related() descends to related models from this model.
  1632. # - local_setter, remote_setter: Methods to set cached values on
  1633. # the object being populated and on the remote object. Usually
  1634. # these are Field.set_cached_value() methods.
  1635. select_fields = klass_info['select_fields']
  1636. from_parent = klass_info['from_parent']
  1637. if not from_parent:
  1638. self.cols_start = select_fields[0]
  1639. self.cols_end = select_fields[-1] + 1
  1640. self.init_list = [
  1641. f[0].target.attname for f in select[self.cols_start:self.cols_end]
  1642. ]
  1643. self.reorder_for_init = None
  1644. else:
  1645. attname_indexes = {select[idx][0].target.attname: idx for idx in select_fields}
  1646. model_init_attnames = (f.attname for f in klass_info['model']._meta.concrete_fields)
  1647. self.init_list = [attname for attname in model_init_attnames if attname in attname_indexes]
  1648. self.reorder_for_init = operator.itemgetter(*[attname_indexes[attname] for attname in self.init_list])
  1649. self.model_cls = klass_info['model']
  1650. self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname)
  1651. self.related_populators = get_related_populators(klass_info, select, self.db)
  1652. self.local_setter = klass_info['local_setter']
  1653. self.remote_setter = klass_info['remote_setter']
  1654. def populate(self, row, from_obj):
  1655. if self.reorder_for_init:
  1656. obj_data = self.reorder_for_init(row)
  1657. else:
  1658. obj_data = row[self.cols_start:self.cols_end]
  1659. if obj_data[self.pk_idx] is None:
  1660. obj = None
  1661. else:
  1662. obj = self.model_cls.from_db(self.db, self.init_list, obj_data)
  1663. for rel_iter in self.related_populators:
  1664. rel_iter.populate(row, obj)
  1665. self.local_setter(from_obj, obj)
  1666. if obj is not None:
  1667. self.remote_setter(obj, from_obj)
  1668. def get_related_populators(klass_info, select, db):
  1669. iterators = []
  1670. related_klass_infos = klass_info.get('related_klass_infos', [])
  1671. for rel_klass_info in related_klass_infos:
  1672. rel_cls = RelatedPopulator(rel_klass_info, select, db)
  1673. iterators.append(rel_cls)
  1674. return iterators