manager.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. @python_2_unicode_compatible
  9. class BaseManager(object):
  10. # Tracks each time a Manager instance is created. Used to retain order.
  11. creation_counter = 0
  12. # Set to True for the 'objects' managers that are automatically created.
  13. auto_created = False
  14. #: If set to True the manager will be serialized into migrations and will
  15. #: thus be available in e.g. RunPython operations
  16. use_in_migrations = False
  17. def __new__(cls, *args, **kwargs):
  18. # We capture the arguments to make returning them trivial
  19. obj = super(BaseManager, cls).__new__(cls)
  20. obj._constructor_args = (args, kwargs)
  21. return obj
  22. def __init__(self):
  23. super(BaseManager, self).__init__()
  24. self._set_creation_counter()
  25. self.model = None
  26. self.name = None
  27. self._db = None
  28. self._hints = {}
  29. def __str__(self):
  30. """ Return "app_label.model_label.manager_name". """
  31. return '%s.%s' % (self.model._meta.label, self.name)
  32. def deconstruct(self):
  33. """
  34. Returns a 5-tuple of the form (as_manager (True), manager_class,
  35. queryset_class, args, kwargs).
  36. Raises a ValueError if the manager is dynamically generated.
  37. """
  38. qs_class = self._queryset_class
  39. if getattr(self, '_built_with_as_manager', False):
  40. # using MyQuerySet.as_manager()
  41. return (
  42. True, # as_manager
  43. None, # manager_class
  44. '%s.%s' % (qs_class.__module__, qs_class.__name__), # qs_class
  45. None, # args
  46. None, # kwargs
  47. )
  48. else:
  49. module_name = self.__module__
  50. name = self.__class__.__name__
  51. # Make sure it's actually there and not an inner class
  52. module = import_module(module_name)
  53. if not hasattr(module, name):
  54. raise ValueError(
  55. "Could not find manager %s in %s.\n"
  56. "Please note that you need to inherit from managers you "
  57. "dynamically generated with 'from_queryset()'."
  58. % (name, module_name)
  59. )
  60. return (
  61. False, # as_manager
  62. '%s.%s' % (module_name, name), # manager_class
  63. None, # qs_class
  64. self._constructor_args[0], # args
  65. self._constructor_args[1], # kwargs
  66. )
  67. def check(self, **kwargs):
  68. return []
  69. @classmethod
  70. def _get_queryset_methods(cls, queryset_class):
  71. def create_method(name, method):
  72. def manager_method(self, *args, **kwargs):
  73. return getattr(self.get_queryset(), name)(*args, **kwargs)
  74. manager_method.__name__ = method.__name__
  75. manager_method.__doc__ = method.__doc__
  76. return manager_method
  77. new_methods = {}
  78. # Refs http://bugs.python.org/issue1785.
  79. predicate = inspect.isfunction if six.PY3 else inspect.ismethod
  80. for name, method in inspect.getmembers(queryset_class, predicate=predicate):
  81. # Only copy missing methods.
  82. if hasattr(cls, name):
  83. continue
  84. # Only copy public methods or methods with the attribute `queryset_only=False`.
  85. queryset_only = getattr(method, 'queryset_only', None)
  86. if queryset_only or (queryset_only is None and name.startswith('_')):
  87. continue
  88. # Copy the method onto the manager.
  89. new_methods[name] = create_method(name, method)
  90. return new_methods
  91. @classmethod
  92. def from_queryset(cls, queryset_class, class_name=None):
  93. if class_name is None:
  94. class_name = '%sFrom%s' % (cls.__name__, queryset_class.__name__)
  95. class_dict = {
  96. '_queryset_class': queryset_class,
  97. }
  98. class_dict.update(cls._get_queryset_methods(queryset_class))
  99. return type(class_name, (cls,), class_dict)
  100. def contribute_to_class(self, model, name):
  101. if not self.name:
  102. self.name = name
  103. self.model = model
  104. setattr(model, name, ManagerDescriptor(self))
  105. model._meta.add_manager(self)
  106. def _set_creation_counter(self):
  107. """
  108. Sets the creation counter value for this instance and increments the
  109. class-level copy.
  110. """
  111. self.creation_counter = BaseManager.creation_counter
  112. BaseManager.creation_counter += 1
  113. def db_manager(self, using=None, hints=None):
  114. obj = copy.copy(self)
  115. obj._db = using or self._db
  116. obj._hints = hints or self._hints
  117. return obj
  118. @property
  119. def db(self):
  120. return self._db or router.db_for_read(self.model, **self._hints)
  121. #######################
  122. # PROXIES TO QUERYSET #
  123. #######################
  124. def get_queryset(self):
  125. """
  126. Returns a new QuerySet object. Subclasses can override this method to
  127. easily customize the behavior of the Manager.
  128. """
  129. return self._queryset_class(model=self.model, using=self._db, hints=self._hints)
  130. def all(self):
  131. # We can't proxy this method through the `QuerySet` like we do for the
  132. # rest of the `QuerySet` methods. This is because `QuerySet.all()`
  133. # works by creating a "copy" of the current queryset and in making said
  134. # copy, all the cached `prefetch_related` lookups are lost. See the
  135. # implementation of `RelatedManager.get_queryset()` for a better
  136. # understanding of how this comes into play.
  137. return self.get_queryset()
  138. def __eq__(self, other):
  139. return (
  140. isinstance(other, self.__class__) and
  141. self._constructor_args == other._constructor_args
  142. )
  143. def __ne__(self, other):
  144. return not (self == other)
  145. def __hash__(self):
  146. return id(self)
  147. class Manager(BaseManager.from_queryset(QuerySet)):
  148. pass
  149. class ManagerDescriptor(object):
  150. def __init__(self, manager):
  151. self.manager = manager
  152. def __get__(self, instance, cls=None):
  153. if instance is not None:
  154. raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__)
  155. if cls._meta.abstract:
  156. raise AttributeError("Manager isn't available; %s is abstract" % (
  157. cls._meta.object_name,
  158. ))
  159. if cls._meta.swapped:
  160. raise AttributeError(
  161. "Manager isn't available; '%s.%s' has been swapped for '%s'" % (
  162. cls._meta.app_label,
  163. cls._meta.object_name,
  164. cls._meta.swapped,
  165. )
  166. )
  167. return cls._meta.managers_map[self.manager.name]
  168. class EmptyManager(Manager):
  169. def __init__(self, model):
  170. super(EmptyManager, self).__init__()
  171. self.model = model
  172. def get_queryset(self):
  173. return super(EmptyManager, self).get_queryset().none()