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.
 
 
 
 

1731 lines
68 KiB

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