query_utils.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. from __future__ import unicode_literals
  8. from django.apps import apps
  9. from django.db.backends import utils
  10. from django.db.models.constants import LOOKUP_SEP
  11. from django.utils import six
  12. from django.utils import tree
  13. class InvalidQuery(Exception):
  14. """
  15. The query passed to raw isn't a safe query to use with raw.
  16. """
  17. pass
  18. class QueryWrapper(object):
  19. """
  20. A type that indicates the contents are an SQL fragment and the associate
  21. parameters. Can be used to pass opaque data to a where-clause, for example.
  22. """
  23. def __init__(self, sql, params):
  24. self.data = sql, list(params)
  25. def as_sql(self, qn=None, connection=None):
  26. return self.data
  27. class Q(tree.Node):
  28. """
  29. Encapsulates filters as objects that can then be combined logically (using
  30. & and |).
  31. """
  32. # Connection types
  33. AND = 'AND'
  34. OR = 'OR'
  35. default = AND
  36. def __init__(self, *args, **kwargs):
  37. super(Q, self).__init__(children=list(args) + list(six.iteritems(kwargs)))
  38. def _combine(self, other, conn):
  39. if not isinstance(other, Q):
  40. raise TypeError(other)
  41. obj = type(self)()
  42. obj.connector = conn
  43. obj.add(self, conn)
  44. obj.add(other, conn)
  45. return obj
  46. def __or__(self, other):
  47. return self._combine(other, self.OR)
  48. def __and__(self, other):
  49. return self._combine(other, self.AND)
  50. def __invert__(self):
  51. obj = type(self)()
  52. obj.add(self, self.AND)
  53. obj.negate()
  54. return obj
  55. def clone(self):
  56. clone = self.__class__._new_instance(
  57. children=[], connector=self.connector, negated=self.negated)
  58. for child in self.children:
  59. if hasattr(child, 'clone'):
  60. clone.children.append(child.clone())
  61. else:
  62. clone.children.append(child)
  63. return clone
  64. class DeferredAttribute(object):
  65. """
  66. A wrapper for a deferred-loading field. When the value is read from this
  67. object the first time, the query is executed.
  68. """
  69. def __init__(self, field_name, model):
  70. self.field_name = field_name
  71. def __get__(self, instance, owner):
  72. """
  73. Retrieves and caches the value from the datastore on the first lookup.
  74. Returns the cached value.
  75. """
  76. from django.db.models.fields import FieldDoesNotExist
  77. non_deferred_model = instance._meta.proxy_for_model
  78. opts = non_deferred_model._meta
  79. assert instance is not None
  80. data = instance.__dict__
  81. if data.get(self.field_name, self) is self:
  82. # self.field_name is the attname of the field, but only() takes the
  83. # actual name, so we need to translate it here.
  84. try:
  85. f = opts.get_field_by_name(self.field_name)[0]
  86. except FieldDoesNotExist:
  87. f = [f for f in opts.fields if f.attname == self.field_name][0]
  88. name = f.name
  89. # Let's see if the field is part of the parent chain. If so we
  90. # might be able to reuse the already loaded value. Refs #18343.
  91. val = self._check_parent_chain(instance, name)
  92. if val is None:
  93. # We use only() instead of values() here because we want the
  94. # various data coercion methods (to_python(), etc.) to be
  95. # called here.
  96. val = getattr(
  97. non_deferred_model._base_manager.only(name).using(
  98. instance._state.db).get(pk=instance.pk),
  99. self.field_name
  100. )
  101. data[self.field_name] = val
  102. return data[self.field_name]
  103. def __set__(self, instance, value):
  104. """
  105. Deferred loading attributes can be set normally (which means there will
  106. never be a database lookup involved.
  107. """
  108. instance.__dict__[self.field_name] = value
  109. def _check_parent_chain(self, instance, name):
  110. """
  111. Check if the field value can be fetched from a parent field already
  112. loaded in the instance. This can be done if the to-be fetched
  113. field is a primary key field.
  114. """
  115. opts = instance._meta
  116. f = opts.get_field_by_name(name)[0]
  117. link_field = opts.get_ancestor_link(f.model)
  118. if f.primary_key and f != link_field:
  119. return getattr(instance, link_field.attname)
  120. return None
  121. def select_related_descend(field, restricted, requested, load_fields, reverse=False):
  122. """
  123. Returns True if this field should be used to descend deeper for
  124. select_related() purposes. Used by both the query construction code
  125. (sql.query.fill_related_selections()) and the model instance creation code
  126. (query.get_klass_info()).
  127. Arguments:
  128. * field - the field to be checked
  129. * restricted - a boolean field, indicating if the field list has been
  130. manually restricted using a requested clause)
  131. * requested - The select_related() dictionary.
  132. * load_fields - the set of fields to be loaded on this model
  133. * reverse - boolean, True if we are checking a reverse select related
  134. """
  135. if not field.rel:
  136. return False
  137. if field.rel.parent_link and not reverse:
  138. return False
  139. if restricted:
  140. if reverse and field.related_query_name() not in requested:
  141. return False
  142. if not reverse and field.name not in requested:
  143. return False
  144. if not restricted and field.null:
  145. return False
  146. if load_fields:
  147. if field.name not in load_fields:
  148. if restricted and field.name in requested:
  149. raise InvalidQuery("Field %s.%s cannot be both deferred"
  150. " and traversed using select_related"
  151. " at the same time." %
  152. (field.model._meta.object_name, field.name))
  153. return False
  154. return True
  155. # This function is needed because data descriptors must be defined on a class
  156. # object, not an instance, to have any effect.
  157. def deferred_class_factory(model, attrs):
  158. """
  159. Returns a class object that is a copy of "model" with the specified "attrs"
  160. being replaced with DeferredAttribute objects. The "pk_value" ties the
  161. deferred attributes to a particular instance of the model.
  162. """
  163. if not attrs:
  164. return model
  165. # Never create deferred models based on deferred model
  166. if model._deferred:
  167. # Deferred models are proxies for the non-deferred model. We never
  168. # create chains of defers => proxy_for_model is the non-deferred
  169. # model.
  170. model = model._meta.proxy_for_model
  171. # The app registry wants a unique name for each model, otherwise the new
  172. # class won't be created (we get an exception). Therefore, we generate
  173. # the name using the passed in attrs. It's OK to reuse an existing class
  174. # object if the attrs are identical.
  175. name = "%s_Deferred_%s" % (model.__name__, '_'.join(sorted(list(attrs))))
  176. name = utils.truncate_name(name, 80, 32)
  177. try:
  178. return apps.get_model(model._meta.app_label, name)
  179. except LookupError:
  180. class Meta:
  181. proxy = True
  182. app_label = model._meta.app_label
  183. overrides = dict((attr, DeferredAttribute(attr, model)) for attr in attrs)
  184. overrides["Meta"] = Meta
  185. overrides["__module__"] = model.__module__
  186. overrides["_deferred"] = True
  187. return type(str(name), (model,), overrides)
  188. # The above function is also used to unpickle model instances with deferred
  189. # fields.
  190. deferred_class_factory.__safe_for_unpickling__ = True
  191. def refs_aggregate(lookup_parts, aggregates):
  192. """
  193. A little helper method to check if the lookup_parts contains references
  194. to the given aggregates set. Because the LOOKUP_SEP is contained in the
  195. default annotation names we must check each prefix of the lookup_parts
  196. for a match.
  197. """
  198. for n in range(len(lookup_parts) + 1):
  199. level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n])
  200. if level_n_lookup in aggregates and aggregates[level_n_lookup].contains_aggregate:
  201. return aggregates[level_n_lookup], lookup_parts[n:]
  202. return False, ()