managers.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. A custom ``Manager`` method can return anything you want. It doesn't have to
  42. return a ``QuerySet``.
  43. For example, this custom ``Manager`` offers a method ``with_counts()``, which
  44. returns a list of all ``OpinionPoll`` objects, each with an extra
  45. ``num_responses`` attribute that is the result of an aggregate query::
  46. from django.db import models
  47. class PollManager(models.Manager):
  48. def with_counts(self):
  49. from django.db import connection
  50. cursor = connection.cursor()
  51. cursor.execute("""
  52. SELECT p.id, p.question, p.poll_date, COUNT(*)
  53. FROM polls_opinionpoll p, polls_response r
  54. WHERE p.id = r.poll_id
  55. GROUP BY p.id, p.question, p.poll_date
  56. ORDER BY p.poll_date DESC""")
  57. result_list = []
  58. for row in cursor.fetchall():
  59. p = self.model(id=row[0], question=row[1], poll_date=row[2])
  60. p.num_responses = row[3]
  61. result_list.append(p)
  62. return result_list
  63. class OpinionPoll(models.Model):
  64. question = models.CharField(max_length=200)
  65. poll_date = models.DateField()
  66. objects = PollManager()
  67. class Response(models.Model):
  68. poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)
  69. person_name = models.CharField(max_length=50)
  70. response = models.TextField()
  71. With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return
  72. that list of ``OpinionPoll`` objects with ``num_responses`` attributes.
  73. Another thing to note about this example is that ``Manager`` methods can
  74. access ``self.model`` to get the model class to which they're attached.
  75. Modifying initial Manager QuerySets
  76. -----------------------------------
  77. A ``Manager``’s base ``QuerySet`` returns all objects in the system. For
  78. example, using this model::
  79. from django.db import models
  80. class Book(models.Model):
  81. title = models.CharField(max_length=100)
  82. author = models.CharField(max_length=50)
  83. ...the statement ``Book.objects.all()`` will return all books in the database.
  84. You can override a ``Manager``’s base ``QuerySet`` by overriding the
  85. ``Manager.get_queryset()`` method. ``get_queryset()`` should return a
  86. ``QuerySet`` with the properties you require.
  87. For example, the following model has *two* ``Manager``\s -- one that returns
  88. all objects, and one that returns only the books by Roald Dahl::
  89. # First, define the Manager subclass.
  90. class DahlBookManager(models.Manager):
  91. def get_queryset(self):
  92. return super(DahlBookManager, self).get_queryset().filter(author='Roald Dahl')
  93. # Then hook it into the Book model explicitly.
  94. class Book(models.Model):
  95. title = models.CharField(max_length=100)
  96. author = models.CharField(max_length=50)
  97. objects = models.Manager() # The default manager.
  98. dahl_objects = DahlBookManager() # The Dahl-specific manager.
  99. With this sample model, ``Book.objects.all()`` will return all books in the
  100. database, but ``Book.dahl_objects.all()`` will only return the ones written by
  101. Roald Dahl.
  102. Of course, because ``get_queryset()`` returns a ``QuerySet`` object, you can
  103. use ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it.
  104. So these statements are all legal::
  105. Book.dahl_objects.all()
  106. Book.dahl_objects.filter(title='Matilda')
  107. Book.dahl_objects.count()
  108. This example also pointed out another interesting technique: using multiple
  109. managers on the same model. You can attach as many ``Manager()`` instances to
  110. a model as you'd like. This is an easy way to define common "filters" for your
  111. models.
  112. For example::
  113. class AuthorManager(models.Manager):
  114. def get_queryset(self):
  115. return super(AuthorManager, self).get_queryset().filter(role='A')
  116. class EditorManager(models.Manager):
  117. def get_queryset(self):
  118. return super(EditorManager, self).get_queryset().filter(role='E')
  119. class Person(models.Model):
  120. first_name = models.CharField(max_length=50)
  121. last_name = models.CharField(max_length=50)
  122. role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor'))))
  123. people = models.Manager()
  124. authors = AuthorManager()
  125. editors = EditorManager()
  126. This example allows you to request ``Person.authors.all()``, ``Person.editors.all()``,
  127. and ``Person.people.all()``, yielding predictable results.
  128. .. _default-managers:
  129. Default managers
  130. ~~~~~~~~~~~~~~~~
  131. If you use custom ``Manager`` objects, take note that the first ``Manager``
  132. Django encounters (in the order in which they're defined in the model) has a
  133. special status. Django interprets the first ``Manager`` defined in a class as
  134. the "default" ``Manager``, and several parts of Django
  135. (including :djadmin:`dumpdata`) will use that ``Manager``
  136. exclusively for that model. As a result, it's a good idea to be careful in
  137. your choice of default manager in order to avoid a situation where overriding
  138. ``get_queryset()`` results in an inability to retrieve objects you'd like to
  139. work with.
  140. .. _managers-for-related-objects:
  141. Using managers for related object access
  142. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  143. By default, Django uses an instance of a "plain" manager class when accessing
  144. related objects (i.e. ``choice.poll``), not the default manager on the related
  145. object. This is because Django needs to be able to retrieve the related
  146. object, even if it would otherwise be filtered out (and hence be inaccessible)
  147. by the default manager.
  148. If the normal plain manager class (:class:`django.db.models.Manager`) is not
  149. appropriate for your circumstances, you can force Django to use the same class
  150. as the default manager for your model by setting the ``use_for_related_fields``
  151. attribute on the manager class. This is documented fully below_.
  152. .. _below: manager-types_
  153. .. _calling-custom-queryset-methods-from-manager:
  154. Calling custom ``QuerySet`` methods from the ``Manager``
  155. --------------------------------------------------------
  156. While most methods from the standard ``QuerySet`` are accessible directly from
  157. the ``Manager``, this is only the case for the extra methods defined on a
  158. custom ``QuerySet`` if you also implement them on the ``Manager``::
  159. class PersonQuerySet(models.QuerySet):
  160. def authors(self):
  161. return self.filter(role='A')
  162. def editors(self):
  163. return self.filter(role='E')
  164. class PersonManager(models.Manager):
  165. def get_queryset(self):
  166. return PersonQuerySet(self.model, using=self._db)
  167. def authors(self):
  168. return self.get_queryset().authors()
  169. def editors(self):
  170. return self.get_queryset().editors()
  171. class Person(models.Model):
  172. first_name = models.CharField(max_length=50)
  173. last_name = models.CharField(max_length=50)
  174. role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor'))))
  175. people = PersonManager()
  176. This example allows you to call both ``authors()`` and ``editors()`` directly from
  177. the manager ``Person.people``.
  178. .. _create-manager-with-queryset-methods:
  179. Creating ``Manager`` with ``QuerySet`` methods
  180. ----------------------------------------------
  181. In lieu of the above approach which requires duplicating methods on both the
  182. ``QuerySet`` and the ``Manager``, :meth:`QuerySet.as_manager()
  183. <django.db.models.query.QuerySet.as_manager>` can be used to create an instance
  184. of ``Manager`` with a copy of a custom ``QuerySet``’s methods::
  185. class Person(models.Model):
  186. ...
  187. people = PersonQuerySet.as_manager()
  188. The ``Manager`` instance created by :meth:`QuerySet.as_manager()
  189. <django.db.models.query.QuerySet.as_manager>` will be virtually
  190. identical to the ``PersonManager`` from the previous example.
  191. Not every ``QuerySet`` method makes sense at the ``Manager`` level; for
  192. instance we intentionally prevent the :meth:`QuerySet.delete()
  193. <django.db.models.query.QuerySet.delete>` method from being copied onto
  194. the ``Manager`` class.
  195. Methods are copied according to the following rules:
  196. - Public methods are copied by default.
  197. - Private methods (starting with an underscore) are not copied by default.
  198. - Methods with a ``queryset_only`` attribute set to ``False`` are always copied.
  199. - Methods with a ``queryset_only`` attribute set to ``True`` are never copied.
  200. For example::
  201. class CustomQuerySet(models.QuerySet):
  202. # Available on both Manager and QuerySet.
  203. def public_method(self):
  204. return
  205. # Available only on QuerySet.
  206. def _private_method(self):
  207. return
  208. # Available only on QuerySet.
  209. def opted_out_public_method(self):
  210. return
  211. opted_out_public_method.queryset_only = True
  212. # Available on both Manager and QuerySet.
  213. def _opted_in_private_method(self):
  214. return
  215. _opted_in_private_method.queryset_only = False
  216. from_queryset
  217. ~~~~~~~~~~~~~
  218. .. classmethod:: from_queryset(queryset_class)
  219. For advanced usage you might want both a custom ``Manager`` and a custom
  220. ``QuerySet``. You can do that by calling ``Manager.from_queryset()`` which
  221. returns a *subclass* of your base ``Manager`` with a copy of the custom
  222. ``QuerySet`` methods::
  223. class BaseManager(models.Manager):
  224. def manager_only_method(self):
  225. return
  226. class CustomQuerySet(models.QuerySet):
  227. def manager_and_queryset_method(self):
  228. return
  229. class MyModel(models.Model):
  230. objects = BaseManager.from_queryset(CustomQuerySet)()
  231. You may also store the generated class into a variable::
  232. CustomManager = BaseManager.from_queryset(CustomQuerySet)
  233. class MyModel(models.Model):
  234. objects = CustomManager()
  235. .. _custom-managers-and-inheritance:
  236. Custom managers and model inheritance
  237. -------------------------------------
  238. Class inheritance and model managers aren't quite a perfect match for each
  239. other. Managers are often specific to the classes they are defined on and
  240. inheriting them in subclasses isn't necessarily a good idea. Also, because the
  241. first manager declared is the *default manager*, it is important to allow that
  242. to be controlled. So here's how Django handles custom managers and
  243. :ref:`model inheritance <model-inheritance>`:
  244. 1. Managers defined on non-abstract base classes are *not* inherited by
  245. child classes. If you want to reuse a manager from a non-abstract base,
  246. redeclare it explicitly on the child class. These sorts of managers are
  247. likely to be fairly specific to the class they are defined on, so
  248. inheriting them can often lead to unexpected results (particularly as
  249. far as the default manager goes). Therefore, they aren't passed onto
  250. child classes.
  251. 2. Managers from abstract base classes are always inherited by the child
  252. class, using Python's normal name resolution order (names on the child
  253. class override all others; then come names on the first parent class,
  254. and so on). Abstract base classes are designed to capture information
  255. and behavior that is common to their child classes. Defining common
  256. managers is an appropriate part of this common information.
  257. 3. The default manager on a class is either the first manager declared on
  258. the class, if that exists, or the default manager of the first abstract
  259. base class in the parent hierarchy, if that exists. If no default
  260. manager is explicitly declared, Django's normal default manager is
  261. used.
  262. These rules provide the necessary flexibility if you want to install a
  263. collection of custom managers on a group of models, via an abstract base
  264. class, but still customize the default manager. For example, suppose you have
  265. this base class::
  266. class AbstractBase(models.Model):
  267. # ...
  268. objects = CustomManager()
  269. class Meta:
  270. abstract = True
  271. If you use this directly in a subclass, ``objects`` will be the default
  272. manager if you declare no managers in the base class::
  273. class ChildA(AbstractBase):
  274. # ...
  275. # This class has CustomManager as the default manager.
  276. pass
  277. If you want to inherit from ``AbstractBase``, but provide a different default
  278. manager, you can provide the default manager on the child class::
  279. class ChildB(AbstractBase):
  280. # ...
  281. # An explicit default manager.
  282. default_manager = OtherManager()
  283. Here, ``default_manager`` is the default. The ``objects`` manager is
  284. still available, since it's inherited. It just isn't used as the default.
  285. Finally for this example, suppose you want to add extra managers to the child
  286. class, but still use the default from ``AbstractBase``. You can't add the new
  287. manager directly in the child class, as that would override the default and you would
  288. have to also explicitly include all the managers from the abstract base class.
  289. The solution is to put the extra managers in another base class and introduce
  290. it into the inheritance hierarchy *after* the defaults::
  291. class ExtraManager(models.Model):
  292. extra_manager = OtherManager()
  293. class Meta:
  294. abstract = True
  295. class ChildC(AbstractBase, ExtraManager):
  296. # ...
  297. # Default manager is CustomManager, but OtherManager is
  298. # also available via the "extra_manager" attribute.
  299. pass
  300. Note that while you can *define* a custom manager on the abstract model, you
  301. can't *invoke* any methods using the abstract model. That is::
  302. ClassA.objects.do_something()
  303. is legal, but::
  304. AbstractBase.objects.do_something()
  305. will raise an exception. This is because managers are intended to encapsulate
  306. logic for managing collections of objects. Since you can't have a collection of
  307. abstract objects, it doesn't make sense to be managing them. If you have
  308. functionality that applies to the abstract model, you should put that functionality
  309. in a ``staticmethod`` or ``classmethod`` on the abstract model.
  310. Implementation concerns
  311. -----------------------
  312. Whatever features you add to your custom ``Manager``, it must be
  313. possible to make a shallow copy of a ``Manager`` instance; i.e., the
  314. following code must work::
  315. >>> import copy
  316. >>> manager = MyManager()
  317. >>> my_copy = copy.copy(manager)
  318. Django makes shallow copies of manager objects during certain queries;
  319. if your Manager cannot be copied, those queries will fail.
  320. This won't be an issue for most custom managers. If you are just
  321. adding simple methods to your ``Manager``, it is unlikely that you
  322. will inadvertently make instances of your ``Manager`` uncopyable.
  323. However, if you're overriding ``__getattr__`` or some other private
  324. method of your ``Manager`` object that controls object state, you
  325. should ensure that you don't affect the ability of your ``Manager`` to
  326. be copied.
  327. .. _manager-types:
  328. Controlling automatic Manager types
  329. ===================================
  330. This document has already mentioned a couple of places where Django creates a
  331. manager class for you: `default managers`_ and the "plain" manager used to
  332. `access related objects`_. There are other places in the implementation of
  333. Django where temporary plain managers are needed. Those automatically created
  334. managers will normally be instances of the :class:`django.db.models.Manager`
  335. class.
  336. .. _default managers: manager-names_
  337. .. _access related objects: managers-for-related-objects_
  338. Throughout this section, we will use the term "automatic manager" to mean a
  339. manager that Django creates for you -- either as a default manager on a model
  340. with no managers, or to use temporarily when accessing related objects.
  341. Sometimes this default class won't be the right choice. The default manager
  342. may not have all the methods you need to work with your data. A custom manager
  343. class of your own will allow you to create custom ``QuerySet`` objects to give
  344. you the information you need.
  345. Django provides a way for custom manager developers to say that their manager
  346. class should be used for automatic managers whenever it is the default manager
  347. on a model. This is done by setting the ``use_for_related_fields`` attribute on
  348. the manager class::
  349. class MyManager(models.Manager):
  350. use_for_related_fields = True
  351. # ...
  352. If this attribute is set on the *default* manager for a model (only the
  353. default manager is considered in these situations), Django will use that class
  354. whenever it needs to automatically create a manager for the class. Otherwise,
  355. it will use :class:`django.db.models.Manager`.
  356. .. admonition:: Historical Note
  357. Given the purpose for which it's used, the name of this attribute
  358. (``use_for_related_fields``) might seem a little odd. Originally, the
  359. attribute only controlled the type of manager used for related field
  360. access, which is where the name came from. As it became clear the concept
  361. was more broadly useful, the name hasn't been changed. This is primarily
  362. so that existing code will :doc:`continue to work </misc/api-stability>` in
  363. future Django versions.
  364. Writing correct Managers for use in automatic Manager instances
  365. ---------------------------------------------------------------
  366. The ``use_for_related_fields`` feature is primarily for managers that need to
  367. return a custom ``QuerySet`` subclass. In providing this functionality in your
  368. manager, there are a couple of things to remember.
  369. Do not filter away any results in this type of manager subclass
  370. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  371. One reason an automatic manager is used is to access objects that are related
  372. to from some other model. In those situations, Django has to be able to see
  373. all the objects for the model it is fetching, so that *anything* which is
  374. referred to can be retrieved.
  375. If you override the ``get_queryset()`` method and filter out any rows, Django
  376. will return incorrect results. Don't do that. A manager that filters results
  377. in ``get_queryset()`` is not appropriate for use as an automatic manager.
  378. Set ``use_for_related_fields`` when you define the class
  379. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  380. The ``use_for_related_fields`` attribute must be set on the manager *class*, not
  381. on an *instance* of the class. The earlier example shows the correct way to set
  382. it, whereas the following will not work::
  383. # BAD: Incorrect code
  384. class MyManager(models.Manager):
  385. # ...
  386. pass
  387. # Sets the attribute on an instance of MyManager. Django will
  388. # ignore this setting.
  389. mgr = MyManager()
  390. mgr.use_for_related_fields = True
  391. class MyModel(models.Model):
  392. # ...
  393. objects = mgr
  394. # End of incorrect code.
  395. You also shouldn't change the attribute on the class object after it has been
  396. used in a model, since the attribute's value is processed when the model class
  397. is created and not subsequently reread. Set the attribute on the manager class
  398. when it is first defined, as in the initial example of this section and
  399. everything will work smoothly.