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