Development of an internal social media platform with personalised dashboards for students
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

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