query.py 79 KB

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