2
0

manager.py 10 KB

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