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

query_utils.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. """
  2. Various data structures used in query construction.
  3. Factored out from django.db.models.query to avoid making the main module very
  4. large and/or so that they can be used by other modules without getting into
  5. circular import difficulties.
  6. """
  7. import copy
  8. import functools
  9. import inspect
  10. from collections import namedtuple
  11. from django.db.models.constants import LOOKUP_SEP
  12. from django.utils import tree
  13. # PathInfo is used when converting lookups (fk__somecol). The contents
  14. # describe the relation in Model terms (model Options and Fields for both
  15. # sides of the relation. The join_field is the field backing the relation.
  16. PathInfo = namedtuple('PathInfo', 'from_opts to_opts target_fields join_field m2m direct filtered_relation')
  17. class InvalidQuery(Exception):
  18. """The query passed to raw() isn't a safe query to use with raw()."""
  19. pass
  20. def subclasses(cls):
  21. yield cls
  22. for subclass in cls.__subclasses__():
  23. yield from subclasses(subclass)
  24. class QueryWrapper:
  25. """
  26. A type that indicates the contents are an SQL fragment and the associate
  27. parameters. Can be used to pass opaque data to a where-clause, for example.
  28. """
  29. contains_aggregate = False
  30. def __init__(self, sql, params):
  31. self.data = sql, list(params)
  32. def as_sql(self, compiler=None, connection=None):
  33. return self.data
  34. class Q(tree.Node):
  35. """
  36. Encapsulate filters as objects that can then be combined logically (using
  37. `&` and `|`).
  38. """
  39. # Connection types
  40. AND = 'AND'
  41. OR = 'OR'
  42. default = AND
  43. conditional = True
  44. def __init__(self, *args, _connector=None, _negated=False, **kwargs):
  45. super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated)
  46. def _combine(self, other, conn):
  47. if not isinstance(other, Q):
  48. raise TypeError(other)
  49. # If the other Q() is empty, ignore it and just use `self`.
  50. if not other:
  51. return copy.deepcopy(self)
  52. # Or if this Q is empty, ignore it and just use `other`.
  53. elif not self:
  54. return copy.deepcopy(other)
  55. obj = type(self)()
  56. obj.connector = conn
  57. obj.add(self, conn)
  58. obj.add(other, conn)
  59. return obj
  60. def __or__(self, other):
  61. return self._combine(other, self.OR)
  62. def __and__(self, other):
  63. return self._combine(other, self.AND)
  64. def __invert__(self):
  65. obj = type(self)()
  66. obj.add(self, self.AND)
  67. obj.negate()
  68. return obj
  69. def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
  70. # We must promote any new joins to left outer joins so that when Q is
  71. # used as an expression, rows aren't filtered due to joins.
  72. clause, joins = query._add_q(self, reuse, allow_joins=allow_joins, split_subq=False)
  73. query.promote_joins(joins)
  74. return clause
  75. def deconstruct(self):
  76. path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  77. if path.startswith('django.db.models.query_utils'):
  78. path = path.replace('django.db.models.query_utils', 'django.db.models')
  79. args, kwargs = (), {}
  80. if len(self.children) == 1 and not isinstance(self.children[0], Q):
  81. child = self.children[0]
  82. kwargs = {child[0]: child[1]}
  83. else:
  84. args = tuple(self.children)
  85. if self.connector != self.default:
  86. kwargs = {'_connector': self.connector}
  87. if self.negated:
  88. kwargs['_negated'] = True
  89. return path, args, kwargs
  90. class DeferredAttribute:
  91. """
  92. A wrapper for a deferred-loading field. When the value is read from this
  93. object the first time, the query is executed.
  94. """
  95. def __init__(self, field_name):
  96. self.field_name = field_name
  97. def __get__(self, instance, cls=None):
  98. """
  99. Retrieve and caches the value from the datastore on the first lookup.
  100. Return the cached value.
  101. """
  102. if instance is None:
  103. return self
  104. data = instance.__dict__
  105. if data.get(self.field_name, self) is self:
  106. # Let's see if the field is part of the parent chain. If so we
  107. # might be able to reuse the already loaded value. Refs #18343.
  108. val = self._check_parent_chain(instance, self.field_name)
  109. if val is None:
  110. instance.refresh_from_db(fields=[self.field_name])
  111. val = getattr(instance, self.field_name)
  112. data[self.field_name] = val
  113. return data[self.field_name]
  114. def _check_parent_chain(self, instance, name):
  115. """
  116. Check if the field value can be fetched from a parent field already
  117. loaded in the instance. This can be done if the to-be fetched
  118. field is a primary key field.
  119. """
  120. opts = instance._meta
  121. f = opts.get_field(name)
  122. link_field = opts.get_ancestor_link(f.model)
  123. if f.primary_key and f != link_field:
  124. return getattr(instance, link_field.attname)
  125. return None
  126. class RegisterLookupMixin:
  127. @classmethod
  128. def _get_lookup(cls, lookup_name):
  129. return cls.get_lookups().get(lookup_name, None)
  130. @classmethod
  131. @functools.lru_cache(maxsize=None)
  132. def get_lookups(cls):
  133. class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
  134. return cls.merge_dicts(class_lookups)
  135. def get_lookup(self, lookup_name):
  136. from django.db.models.lookups import Lookup
  137. found = self._get_lookup(lookup_name)
  138. if found is None and hasattr(self, 'output_field'):
  139. return self.output_field.get_lookup(lookup_name)
  140. if found is not None and not issubclass(found, Lookup):
  141. return None
  142. return found
  143. def get_transform(self, lookup_name):
  144. from django.db.models.lookups import Transform
  145. found = self._get_lookup(lookup_name)
  146. if found is None and hasattr(self, 'output_field'):
  147. return self.output_field.get_transform(lookup_name)
  148. if found is not None and not issubclass(found, Transform):
  149. return None
  150. return found
  151. @staticmethod
  152. def merge_dicts(dicts):
  153. """
  154. Merge dicts in reverse to preference the order of the original list. e.g.,
  155. merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
  156. """
  157. merged = {}
  158. for d in reversed(dicts):
  159. merged.update(d)
  160. return merged
  161. @classmethod
  162. def _clear_cached_lookups(cls):
  163. for subclass in subclasses(cls):
  164. subclass.get_lookups.cache_clear()
  165. @classmethod
  166. def register_lookup(cls, lookup, lookup_name=None):
  167. if lookup_name is None:
  168. lookup_name = lookup.lookup_name
  169. if 'class_lookups' not in cls.__dict__:
  170. cls.class_lookups = {}
  171. cls.class_lookups[lookup_name] = lookup
  172. cls._clear_cached_lookups()
  173. return lookup
  174. @classmethod
  175. def _unregister_lookup(cls, lookup, lookup_name=None):
  176. """
  177. Remove given lookup from cls lookups. For use in tests only as it's
  178. not thread-safe.
  179. """
  180. if lookup_name is None:
  181. lookup_name = lookup.lookup_name
  182. del cls.class_lookups[lookup_name]
  183. def select_related_descend(field, restricted, requested, load_fields, reverse=False):
  184. """
  185. Return True if this field should be used to descend deeper for
  186. select_related() purposes. Used by both the query construction code
  187. (sql.query.fill_related_selections()) and the model instance creation code
  188. (query.get_klass_info()).
  189. Arguments:
  190. * field - the field to be checked
  191. * restricted - a boolean field, indicating if the field list has been
  192. manually restricted using a requested clause)
  193. * requested - The select_related() dictionary.
  194. * load_fields - the set of fields to be loaded on this model
  195. * reverse - boolean, True if we are checking a reverse select related
  196. """
  197. if not field.remote_field:
  198. return False
  199. if field.remote_field.parent_link and not reverse:
  200. return False
  201. if restricted:
  202. if reverse and field.related_query_name() not in requested:
  203. return False
  204. if not reverse and field.name not in requested:
  205. return False
  206. if not restricted and field.null:
  207. return False
  208. if load_fields:
  209. if field.attname not in load_fields:
  210. if restricted and field.name in requested:
  211. raise InvalidQuery("Field %s.%s cannot be both deferred"
  212. " and traversed using select_related"
  213. " at the same time." %
  214. (field.model._meta.object_name, field.name))
  215. return True
  216. def refs_expression(lookup_parts, annotations):
  217. """
  218. Check if the lookup_parts contains references to the given annotations set.
  219. Because the LOOKUP_SEP is contained in the default annotation names, check
  220. each prefix of the lookup_parts for a match.
  221. """
  222. for n in range(1, len(lookup_parts) + 1):
  223. level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
  224. if level_n_lookup in annotations and annotations[level_n_lookup]:
  225. return annotations[level_n_lookup], lookup_parts[n:]
  226. return False, ()
  227. def check_rel_lookup_compatibility(model, target_opts, field):
  228. """
  229. Check that self.model is compatible with target_opts. Compatibility
  230. is OK if:
  231. 1) model and opts match (where proxy inheritance is removed)
  232. 2) model is parent of opts' model or the other way around
  233. """
  234. def check(opts):
  235. return (
  236. model._meta.concrete_model == opts.concrete_model or
  237. opts.concrete_model in model._meta.get_parent_list() or
  238. model in opts.get_parent_list()
  239. )
  240. # If the field is a primary key, then doing a query against the field's
  241. # model is ok, too. Consider the case:
  242. # class Restaurant(models.Model):
  243. # place = OnetoOneField(Place, primary_key=True):
  244. # Restaurant.objects.filter(pk__in=Restaurant.objects.all()).
  245. # If we didn't have the primary key check, then pk__in (== place__in) would
  246. # give Place's opts as the target opts, but Restaurant isn't compatible
  247. # with that. This logic applies only to primary keys, as when doing __in=qs,
  248. # we are going to turn this into __in=qs.values('pk') later on.
  249. return (
  250. check(target_opts) or
  251. (getattr(field, 'primary_key', False) and check(field.model._meta))
  252. )
  253. class FilteredRelation:
  254. """Specify custom filtering in the ON clause of SQL joins."""
  255. def __init__(self, relation_name, *, condition=Q()):
  256. if not relation_name:
  257. raise ValueError('relation_name cannot be empty.')
  258. self.relation_name = relation_name
  259. self.alias = None
  260. if not isinstance(condition, Q):
  261. raise ValueError('condition argument must be a Q() instance.')
  262. self.condition = condition
  263. self.path = []
  264. def __eq__(self, other):
  265. return (
  266. isinstance(other, self.__class__) and
  267. self.relation_name == other.relation_name and
  268. self.alias == other.alias and
  269. self.condition == other.condition
  270. )
  271. def clone(self):
  272. clone = FilteredRelation(self.relation_name, condition=self.condition)
  273. clone.alias = self.alias
  274. clone.path = self.path[:]
  275. return clone
  276. def resolve_expression(self, *args, **kwargs):
  277. """
  278. QuerySet.annotate() only accepts expression-like arguments
  279. (with a resolve_expression() method).
  280. """
  281. raise NotImplementedError('FilteredRelation.resolve_expression() is unused.')
  282. def as_sql(self, compiler, connection):
  283. # Resolve the condition in Join.filtered_relation.
  284. query = compiler.query
  285. where = query.build_filtered_relation_q(self.condition, reuse=set(self.path))
  286. return compiler.compile(where)