2
0

managers.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. ========
  2. Managers
  3. ========
  4. .. currentmodule:: django.db.models
  5. .. class:: Manager()
  6. A ``Manager`` is the interface through which database query operations are
  7. provided to Django models. At least one ``Manager`` exists for every model in
  8. a Django application.
  9. The way ``Manager`` classes work is documented in :doc:`/topics/db/queries`;
  10. this document specifically touches on model options that customize ``Manager``
  11. behavior.
  12. .. _manager-names:
  13. Manager names
  14. =============
  15. By default, Django adds a ``Manager`` with the name ``objects`` to every Django
  16. model class. However, if you want to use ``objects`` as a field name, or if you
  17. want to use a name other than ``objects`` for the ``Manager``, you can rename
  18. it on a per-model basis. To rename the ``Manager`` for a given class, define a
  19. class attribute of type ``models.Manager()`` on that model. For example::
  20. from django.db import models
  21. class Person(models.Model):
  22. # ...
  23. people = models.Manager()
  24. Using this example model, ``Person.objects`` will generate an
  25. ``AttributeError`` exception, but ``Person.people.all()`` will provide a list
  26. of all ``Person`` objects.
  27. .. _custom-managers:
  28. Custom managers
  29. ===============
  30. You can use a custom ``Manager`` in a particular model by extending the base
  31. ``Manager`` class and instantiating your custom ``Manager`` in your model.
  32. There are two reasons you might want to customize a ``Manager``: to add extra
  33. ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
  34. returns.
  35. Adding extra manager methods
  36. ----------------------------
  37. Adding extra ``Manager`` methods is the preferred way to add "table-level"
  38. functionality to your models. (For "row-level" functionality -- i.e., functions
  39. that act on a single instance of a model object -- use :ref:`Model methods
  40. <model-methods>`, not custom ``Manager`` methods.)
  41. For example, this custom ``Manager`` adds a method ``with_counts()``::
  42. from django.db import models
  43. from django.db.models.functions import Coalesce
  44. class PollManager(models.Manager):
  45. def with_counts(self):
  46. return self.annotate(num_responses=Coalesce(models.Count("response"), 0))
  47. class OpinionPoll(models.Model):
  48. question = models.CharField(max_length=200)
  49. objects = PollManager()
  50. class Response(models.Model):
  51. poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)
  52. # ...
  53. With this example, you'd use ``OpinionPoll.objects.with_counts()`` to get a
  54. ``QuerySet`` of ``OpinionPoll`` objects with the extra ``num_responses``
  55. attribute attached.
  56. A custom ``Manager`` method can return anything you want. It doesn't have to
  57. return a ``QuerySet``.
  58. Another thing to note is that ``Manager`` methods can access ``self.model`` to
  59. get the model class to which they're attached.
  60. Modifying a manager's initial ``QuerySet``
  61. ------------------------------------------
  62. A ``Manager``’s base ``QuerySet`` returns all objects in the system. For
  63. example, using this model::
  64. from django.db import models
  65. class Book(models.Model):
  66. title = models.CharField(max_length=100)
  67. author = models.CharField(max_length=50)
  68. ...the statement ``Book.objects.all()`` will return all books in the database.
  69. You can override a ``Manager``’s base ``QuerySet`` by overriding the
  70. ``Manager.get_queryset()`` method. ``get_queryset()`` should return a
  71. ``QuerySet`` with the properties you require.
  72. For example, the following model has *two* ``Manager``\s -- one that returns
  73. all objects, and one that returns only the books by Roald Dahl::
  74. # First, define the Manager subclass.
  75. class DahlBookManager(models.Manager):
  76. def get_queryset(self):
  77. return super().get_queryset().filter(author="Roald Dahl")
  78. # Then hook it into the Book model explicitly.
  79. class Book(models.Model):
  80. title = models.CharField(max_length=100)
  81. author = models.CharField(max_length=50)
  82. objects = models.Manager() # The default manager.
  83. dahl_objects = DahlBookManager() # The Dahl-specific manager.
  84. With this sample model, ``Book.objects.all()`` will return all books in the
  85. database, but ``Book.dahl_objects.all()`` will only return the ones written by
  86. Roald Dahl.
  87. Because ``get_queryset()`` returns a ``QuerySet`` object, you can use
  88. ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it. So
  89. these statements are all legal::
  90. Book.dahl_objects.all()
  91. Book.dahl_objects.filter(title="Matilda")
  92. Book.dahl_objects.count()
  93. This example also pointed out another interesting technique: using multiple
  94. managers on the same model. You can attach as many ``Manager()`` instances to
  95. a model as you'd like. This is a non-repetitive way to define common "filters"
  96. for your models.
  97. For example::
  98. class AuthorManager(models.Manager):
  99. def get_queryset(self):
  100. return super().get_queryset().filter(role="A")
  101. class EditorManager(models.Manager):
  102. def get_queryset(self):
  103. return super().get_queryset().filter(role="E")
  104. class Person(models.Model):
  105. first_name = models.CharField(max_length=50)
  106. last_name = models.CharField(max_length=50)
  107. role = models.CharField(max_length=1, choices={"A": _("Author"), "E": _("Editor")})
  108. people = models.Manager()
  109. authors = AuthorManager()
  110. editors = EditorManager()
  111. This example allows you to request ``Person.authors.all()``, ``Person.editors.all()``,
  112. and ``Person.people.all()``, yielding predictable results.
  113. .. _default-managers:
  114. Default managers
  115. ----------------
  116. .. attribute:: Model._default_manager
  117. If you use custom ``Manager`` objects, take note that the first ``Manager``
  118. Django encounters (in the order in which they're defined in the model) has a
  119. special status. Django interprets the first ``Manager`` defined in a class as
  120. the "default" ``Manager``, and several parts of Django (including
  121. :djadmin:`dumpdata`) will use that ``Manager`` exclusively for that model. As a
  122. result, it's a good idea to be careful in your choice of default manager in
  123. order to avoid a situation where overriding ``get_queryset()`` results in an
  124. inability to retrieve objects you'd like to work with.
  125. You can specify a custom default manager using :attr:`Meta.default_manager_name
  126. <django.db.models.Options.default_manager_name>`.
  127. If you're writing some code that must handle an unknown model, for example, in
  128. a third-party app that implements a generic view, use this manager (or
  129. :attr:`~Model._base_manager`) rather than assuming the model has an ``objects``
  130. manager.
  131. Base managers
  132. -------------
  133. .. attribute:: Model._base_manager
  134. .. _managers-for-related-objects:
  135. Using managers for related object access
  136. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137. By default, Django uses an instance of the ``Model._base_manager`` manager
  138. class when accessing related objects (i.e. ``choice.question``), not the
  139. ``_default_manager`` on the related object. This is because Django needs to be
  140. able to retrieve the related object, even if it would otherwise be filtered out
  141. (and hence be inaccessible) by the default manager.
  142. If the normal base manager class (:class:`django.db.models.Manager`) isn't
  143. appropriate for your circumstances, you can tell Django which class to use by
  144. setting :attr:`Meta.base_manager_name
  145. <django.db.models.Options.base_manager_name>`.
  146. Base managers aren't used when querying on related models, or when
  147. :ref:`accessing a one-to-many or many-to-many relationship
  148. <backwards-related-objects>`. For example, if the ``Question`` model
  149. :ref:`from the tutorial <creating-models>` had a ``deleted`` field and a base
  150. manager that filters out instances with ``deleted=True``, a queryset like
  151. ``Choice.objects.filter(question__name__startswith='What')`` would include
  152. choices related to deleted questions.
  153. Don't filter away any results in this type of manager subclass
  154. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  155. This manager is used to access objects that are related to from some other
  156. model. In those situations, Django has to be able to see all the objects for
  157. the model it is fetching, so that *anything* which is referred to can be
  158. retrieved.
  159. Therefore, you should not override ``get_queryset()`` to filter out any rows.
  160. If you do so, Django will return incomplete results.
  161. .. _calling-custom-queryset-methods-from-manager:
  162. Calling custom ``QuerySet`` methods from the manager
  163. ----------------------------------------------------
  164. While most methods from the standard ``QuerySet`` are accessible directly from
  165. the ``Manager``, this is only the case for the extra methods defined on a
  166. custom ``QuerySet`` if you also implement them on the ``Manager``::
  167. class PersonQuerySet(models.QuerySet):
  168. def authors(self):
  169. return self.filter(role="A")
  170. def editors(self):
  171. return self.filter(role="E")
  172. class PersonManager(models.Manager):
  173. def get_queryset(self):
  174. return PersonQuerySet(self.model, using=self._db)
  175. def authors(self):
  176. return self.get_queryset().authors()
  177. def editors(self):
  178. return self.get_queryset().editors()
  179. class Person(models.Model):
  180. first_name = models.CharField(max_length=50)
  181. last_name = models.CharField(max_length=50)
  182. role = models.CharField(max_length=1, choices={"A": _("Author"), "E": _("Editor")})
  183. people = PersonManager()
  184. This example allows you to call both ``authors()`` and ``editors()`` directly from
  185. the manager ``Person.people``.
  186. .. _create-manager-with-queryset-methods:
  187. Creating a manager with ``QuerySet`` methods
  188. --------------------------------------------
  189. In lieu of the above approach which requires duplicating methods on both the
  190. ``QuerySet`` and the ``Manager``, :meth:`QuerySet.as_manager()
  191. <django.db.models.query.QuerySet.as_manager>` can be used to create an instance
  192. of ``Manager`` with a copy of a custom ``QuerySet``’s methods::
  193. class Person(models.Model):
  194. ...
  195. people = PersonQuerySet.as_manager()
  196. The ``Manager`` instance created by :meth:`QuerySet.as_manager()
  197. <django.db.models.query.QuerySet.as_manager>` will be virtually
  198. identical to the ``PersonManager`` from the previous example.
  199. Not every ``QuerySet`` method makes sense at the ``Manager`` level; for
  200. instance we intentionally prevent the :meth:`QuerySet.delete()
  201. <django.db.models.query.QuerySet.delete>` method from being copied onto
  202. the ``Manager`` class.
  203. Methods are copied according to the following rules:
  204. - Public methods are copied by default.
  205. - Private methods (starting with an underscore) are not copied by default.
  206. - Methods with a ``queryset_only`` attribute set to ``False`` are always copied.
  207. - Methods with a ``queryset_only`` attribute set to ``True`` are never copied.
  208. For example::
  209. class CustomQuerySet(models.QuerySet):
  210. # Available on both Manager and QuerySet.
  211. def public_method(self):
  212. return
  213. # Available only on QuerySet.
  214. def _private_method(self):
  215. return
  216. # Available only on QuerySet.
  217. def opted_out_public_method(self):
  218. return
  219. opted_out_public_method.queryset_only = True
  220. # Available on both Manager and QuerySet.
  221. def _opted_in_private_method(self):
  222. return
  223. _opted_in_private_method.queryset_only = False
  224. ``from_queryset()``
  225. ~~~~~~~~~~~~~~~~~~~
  226. .. classmethod:: from_queryset(queryset_class)
  227. For advanced usage you might want both a custom ``Manager`` and a custom
  228. ``QuerySet``. You can do that by calling ``Manager.from_queryset()`` which
  229. returns a *subclass* of your base ``Manager`` with a copy of the custom
  230. ``QuerySet`` methods::
  231. class CustomManager(models.Manager):
  232. def manager_only_method(self):
  233. return
  234. class CustomQuerySet(models.QuerySet):
  235. def manager_and_queryset_method(self):
  236. return
  237. class MyModel(models.Model):
  238. objects = CustomManager.from_queryset(CustomQuerySet)()
  239. You may also store the generated class into a variable::
  240. MyManager = CustomManager.from_queryset(CustomQuerySet)
  241. class MyModel(models.Model):
  242. objects = MyManager()
  243. .. _custom-managers-and-inheritance:
  244. Custom managers and model inheritance
  245. -------------------------------------
  246. Here's how Django handles custom managers and :ref:`model inheritance
  247. <model-inheritance>`:
  248. #. Managers from base classes are always inherited by the child class,
  249. using Python's normal name resolution order (names on the child
  250. class override all others; then come names on the first parent class,
  251. and so on).
  252. #. If no managers are declared on a model and/or its parents, Django
  253. automatically creates the ``objects`` manager.
  254. #. The default manager on a class is either the one chosen with
  255. :attr:`Meta.default_manager_name
  256. <django.db.models.Options.default_manager_name>`, or the first manager
  257. declared on the model, or the default manager of the first parent model.
  258. These rules provide the necessary flexibility if you want to install a
  259. collection of custom managers on a group of models, via an abstract base
  260. class, but still customize the default manager. For example, suppose you have
  261. this base class::
  262. class AbstractBase(models.Model):
  263. # ...
  264. objects = CustomManager()
  265. class Meta:
  266. abstract = True
  267. If you use this directly in a child class, ``objects`` will be the default
  268. manager if you declare no managers in the child class::
  269. class ChildA(AbstractBase):
  270. # ...
  271. # This class has CustomManager as the default manager.
  272. pass
  273. If you want to inherit from ``AbstractBase``, but provide a different default
  274. manager, you can provide the default manager on the child class::
  275. class ChildB(AbstractBase):
  276. # ...
  277. # An explicit default manager.
  278. default_manager = OtherManager()
  279. Here, ``default_manager`` is the default. The ``objects`` manager is
  280. still available, since it's inherited, but isn't used as the default.
  281. Finally for this example, suppose you want to add extra managers to the child
  282. class, but still use the default from ``AbstractBase``. You can't add the new
  283. manager directly in the child class, as that would override the default and you would
  284. have to also explicitly include all the managers from the abstract base class.
  285. The solution is to put the extra managers in another base class and introduce
  286. it into the inheritance hierarchy *after* the defaults::
  287. class ExtraManager(models.Model):
  288. extra_manager = OtherManager()
  289. class Meta:
  290. abstract = True
  291. class ChildC(AbstractBase, ExtraManager):
  292. # ...
  293. # Default manager is CustomManager, but OtherManager is
  294. # also available via the "extra_manager" attribute.
  295. pass
  296. Note that while you can *define* a custom manager on the abstract model, you
  297. can't *invoke* any methods using the abstract model. That is::
  298. ClassA.objects.do_something()
  299. is legal, but::
  300. AbstractBase.objects.do_something()
  301. will raise an exception. This is because managers are intended to encapsulate
  302. logic for managing collections of objects. Since you can't have a collection of
  303. abstract objects, it doesn't make sense to be managing them. If you have
  304. functionality that applies to the abstract model, you should put that functionality
  305. in a ``staticmethod`` or ``classmethod`` on the abstract model.
  306. Implementation concerns
  307. -----------------------
  308. Whatever features you add to your custom ``Manager``, it must be
  309. possible to make a shallow copy of a ``Manager`` instance; i.e., the
  310. following code must work:
  311. .. code-block:: pycon
  312. >>> import copy
  313. >>> manager = MyManager()
  314. >>> my_copy = copy.copy(manager)
  315. Django makes shallow copies of manager objects during certain queries;
  316. if your Manager cannot be copied, those queries will fail.
  317. This won't be an issue for most custom managers. If you are just
  318. adding simple methods to your ``Manager``, it is unlikely that you
  319. will inadvertently make instances of your ``Manager`` uncopyable.
  320. However, if you're overriding ``__getattr__`` or some other private
  321. method of your ``Manager`` object that controls object state, you
  322. should ensure that you don't affect the ability of your ``Manager`` to
  323. be copied.