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.
 
 
 
 

289 lines
10 KiB

  1. import copy
  2. import inspect
  3. from importlib import import_module
  4. from django.db import router
  5. from django.db.models.query import QuerySet
  6. from django.utils import six
  7. from django.utils.encoding import python_2_unicode_compatible
  8. def ensure_default_manager(cls):
  9. """
  10. Ensures that a Model subclass contains a default manager and sets the
  11. _default_manager attribute on the class. Also sets up the _base_manager
  12. points to a plain Manager instance (which could be the same as
  13. _default_manager if it's not a subclass of Manager).
  14. """
  15. if cls._meta.swapped:
  16. setattr(cls, 'objects', SwappedManagerDescriptor(cls))
  17. return
  18. if not getattr(cls, '_default_manager', None):
  19. if any(f.name == 'objects' for f in cls._meta.fields):
  20. raise ValueError(
  21. "Model %s must specify a custom Manager, because it has a "
  22. "field named 'objects'" % cls.__name__
  23. )
  24. # Create the default manager, if needed.
  25. cls.add_to_class('objects', Manager())
  26. cls._base_manager = cls.objects
  27. elif not getattr(cls, '_base_manager', None):
  28. default_mgr = cls._default_manager.__class__
  29. if (default_mgr is Manager or
  30. getattr(default_mgr, "use_for_related_fields", False)):
  31. cls._base_manager = cls._default_manager
  32. else:
  33. # Default manager isn't a plain Manager class, or a suitable
  34. # replacement, so we walk up the base class hierarchy until we hit
  35. # something appropriate.
  36. for base_class in default_mgr.mro()[1:]:
  37. if (base_class is Manager or
  38. getattr(base_class, "use_for_related_fields", False)):
  39. cls.add_to_class('_base_manager', base_class())
  40. return
  41. raise AssertionError(
  42. "Should never get here. Please report a bug, including your "
  43. "model and model manager setup."
  44. )
  45. @python_2_unicode_compatible
  46. class BaseManager(object):
  47. # Tracks each time a Manager instance is created. Used to retain order.
  48. creation_counter = 0
  49. #: If set to True the manager will be serialized into migrations and will
  50. #: thus be available in e.g. RunPython operations
  51. use_in_migrations = False
  52. def __new__(cls, *args, **kwargs):
  53. # We capture the arguments to make returning them trivial
  54. obj = super(BaseManager, cls).__new__(cls)
  55. obj._constructor_args = (args, kwargs)
  56. return obj
  57. def __init__(self):
  58. super(BaseManager, self).__init__()
  59. self._set_creation_counter()
  60. self.model = None
  61. self.name = None
  62. self._inherited = False
  63. self._db = None
  64. self._hints = {}
  65. def __str__(self):
  66. """ Return "app_label.model_label.manager_name". """
  67. return '%s.%s' % (self.model._meta.label, self.name)
  68. def deconstruct(self):
  69. """
  70. Returns a 5-tuple of the form (as_manager (True), manager_class,
  71. queryset_class, args, kwargs).
  72. Raises a ValueError if the manager is dynamically generated.
  73. """
  74. qs_class = self._queryset_class
  75. if getattr(self, '_built_with_as_manager', False):
  76. # using MyQuerySet.as_manager()
  77. return (
  78. True, # as_manager
  79. None, # manager_class
  80. '%s.%s' % (qs_class.__module__, qs_class.__name__), # qs_class
  81. None, # args
  82. None, # kwargs
  83. )
  84. else:
  85. module_name = self.__module__
  86. name = self.__class__.__name__
  87. # Make sure it's actually there and not an inner class
  88. module = import_module(module_name)
  89. if not hasattr(module, name):
  90. raise ValueError(
  91. "Could not find manager %s in %s.\n"
  92. "Please note that you need to inherit from managers you "
  93. "dynamically generated with 'from_queryset()'."
  94. % (name, module_name)
  95. )
  96. return (
  97. False, # as_manager
  98. '%s.%s' % (module_name, name), # manager_class
  99. None, # qs_class
  100. self._constructor_args[0], # args
  101. self._constructor_args[1], # kwargs
  102. )
  103. def check(self, **kwargs):
  104. return []
  105. @classmethod
  106. def _get_queryset_methods(cls, queryset_class):
  107. def create_method(name, method):
  108. def manager_method(self, *args, **kwargs):
  109. return getattr(self.get_queryset(), name)(*args, **kwargs)
  110. manager_method.__name__ = method.__name__
  111. manager_method.__doc__ = method.__doc__
  112. return manager_method
  113. new_methods = {}
  114. # Refs http://bugs.python.org/issue1785.
  115. predicate = inspect.isfunction if six.PY3 else inspect.ismethod
  116. for name, method in inspect.getmembers(queryset_class, predicate=predicate):
  117. # Only copy missing methods.
  118. if hasattr(cls, name):
  119. continue
  120. # Only copy public methods or methods with the attribute `queryset_only=False`.
  121. queryset_only = getattr(method, 'queryset_only', None)
  122. if queryset_only or (queryset_only is None and name.startswith('_')):
  123. continue
  124. # Copy the method onto the manager.
  125. new_methods[name] = create_method(name, method)
  126. return new_methods
  127. @classmethod
  128. def from_queryset(cls, queryset_class, class_name=None):
  129. if class_name is None:
  130. class_name = '%sFrom%s' % (cls.__name__, queryset_class.__name__)
  131. class_dict = {
  132. '_queryset_class': queryset_class,
  133. }
  134. class_dict.update(cls._get_queryset_methods(queryset_class))
  135. return type(class_name, (cls,), class_dict)
  136. def contribute_to_class(self, model, name):
  137. # TODO: Use weakref because of possible memory leak / circular reference.
  138. self.model = model
  139. if not self.name:
  140. self.name = name
  141. # Only contribute the manager if the model is concrete
  142. if model._meta.abstract:
  143. setattr(model, name, AbstractManagerDescriptor(model))
  144. elif model._meta.swapped:
  145. setattr(model, name, SwappedManagerDescriptor(model))
  146. else:
  147. # if not model._meta.abstract and not model._meta.swapped:
  148. setattr(model, name, ManagerDescriptor(self))
  149. if (not getattr(model, '_default_manager', None) or
  150. self.creation_counter < model._default_manager.creation_counter):
  151. model._default_manager = self
  152. abstract = False
  153. if model._meta.abstract or (self._inherited and not self.model._meta.proxy):
  154. abstract = True
  155. model._meta.managers.append((self.creation_counter, self, abstract))
  156. def _set_creation_counter(self):
  157. """
  158. Sets the creation counter value for this instance and increments the
  159. class-level copy.
  160. """
  161. self.creation_counter = BaseManager.creation_counter
  162. BaseManager.creation_counter += 1
  163. def _copy_to_model(self, model):
  164. """
  165. Makes a copy of the manager and assigns it to 'model', which should be
  166. a child of the existing model (used when inheriting a manager from an
  167. abstract base class).
  168. """
  169. assert issubclass(model, self.model)
  170. mgr = copy.copy(self)
  171. mgr._set_creation_counter()
  172. mgr.model = model
  173. mgr._inherited = True
  174. return mgr
  175. def db_manager(self, using=None, hints=None):
  176. obj = copy.copy(self)
  177. obj._db = using or self._db
  178. obj._hints = hints or self._hints
  179. return obj
  180. @property
  181. def db(self):
  182. return self._db or router.db_for_read(self.model, **self._hints)
  183. #######################
  184. # PROXIES TO QUERYSET #
  185. #######################
  186. def get_queryset(self):
  187. """
  188. Returns a new QuerySet object. Subclasses can override this method to
  189. easily customize the behavior of the Manager.
  190. """
  191. return self._queryset_class(model=self.model, using=self._db, hints=self._hints)
  192. def all(self):
  193. # We can't proxy this method through the `QuerySet` like we do for the
  194. # rest of the `QuerySet` methods. This is because `QuerySet.all()`
  195. # works by creating a "copy" of the current queryset and in making said
  196. # copy, all the cached `prefetch_related` lookups are lost. See the
  197. # implementation of `RelatedManager.get_queryset()` for a better
  198. # understanding of how this comes into play.
  199. return self.get_queryset()
  200. def __eq__(self, other):
  201. return (
  202. isinstance(other, self.__class__) and
  203. self._constructor_args == other._constructor_args
  204. )
  205. def __ne__(self, other):
  206. return not (self == other)
  207. def __hash__(self):
  208. return id(self)
  209. class Manager(BaseManager.from_queryset(QuerySet)):
  210. pass
  211. class ManagerDescriptor(object):
  212. # This class ensures managers aren't accessible via model instances.
  213. # For example, Poll.objects works, but poll_obj.objects raises AttributeError.
  214. def __init__(self, manager):
  215. self.manager = manager
  216. def __get__(self, instance, type=None):
  217. if instance is not None:
  218. raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
  219. return self.manager
  220. class AbstractManagerDescriptor(object):
  221. # This class provides a better error message when you try to access a
  222. # manager on an abstract model.
  223. def __init__(self, model):
  224. self.model = model
  225. def __get__(self, instance, type=None):
  226. raise AttributeError("Manager isn't available; %s is abstract" % (
  227. self.model._meta.object_name,
  228. ))
  229. class SwappedManagerDescriptor(object):
  230. # This class provides a better error message when you try to access a
  231. # manager on a swapped model.
  232. def __init__(self, model):
  233. self.model = model
  234. def __get__(self, instance, type=None):
  235. raise AttributeError(
  236. "Manager isn't available; '%s.%s' has been swapped for '%s'" % (
  237. self.model._meta.app_label,
  238. self.model._meta.object_name,
  239. self.model._meta.swapped,
  240. )
  241. )
  242. class EmptyManager(Manager):
  243. def __init__(self, model):
  244. super(EmptyManager, self).__init__()
  245. self.model = model
  246. def get_queryset(self):
  247. return super(EmptyManager, self).get_queryset().none()