managers.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. .. _topics-db-managers:
  2. ========
  3. Managers
  4. ========
  5. .. currentmodule:: django.db.models
  6. .. class:: Manager()
  7. A ``Manager`` is the interface through which database query operations are
  8. provided to Django models. At least one ``Manager`` exists for every model in
  9. a Django application.
  10. The way ``Manager`` classes work is documented in :ref:`topics-db-queries`;
  11. this document specifically touches on model options that customize ``Manager``
  12. behavior.
  13. .. _manager-names:
  14. Manager names
  15. =============
  16. By default, Django adds a ``Manager`` with the name ``objects`` to every Django
  17. model class. However, if you want to use ``objects`` as a field name, or if you
  18. want to use a name other than ``objects`` for the ``Manager``, you can rename
  19. it on a per-model basis. To rename the ``Manager`` for a given class, define a
  20. class attribute of type ``models.Manager()`` on that model. For example::
  21. from django.db import models
  22. class Person(models.Model):
  23. #...
  24. people = models.Manager()
  25. Using this example model, ``Person.objects`` will generate an
  26. ``AttributeError`` exception, but ``Person.people.all()`` will provide a list
  27. of all ``Person`` objects.
  28. .. _custom-managers:
  29. Custom Managers
  30. ===============
  31. You can use a custom ``Manager`` in a particular model by extending the base
  32. ``Manager`` class and instantiating your custom ``Manager`` in your model.
  33. There are two reasons you might want to customize a ``Manager``: to add extra
  34. ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
  35. returns.
  36. Adding extra Manager methods
  37. ----------------------------
  38. Adding extra ``Manager`` methods is the preferred way to add "table-level"
  39. functionality to your models. (For "row-level" functionality -- i.e., functions
  40. that act on a single instance of a model object -- use :ref:`Model methods
  41. <model-methods>`, not custom ``Manager`` methods.)
  42. A custom ``Manager`` method can return anything you want. It doesn't have to
  43. return a ``QuerySet``.
  44. For example, this custom ``Manager`` offers a method ``with_counts()``, which
  45. returns a list of all ``OpinionPoll`` objects, each with an extra
  46. ``num_responses`` attribute that is the result of an aggregate query::
  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 1, 2, 3
  56. ORDER BY 3 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(Poll)
  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. class Book(models.Model):
  80. title = models.CharField(max_length=100)
  81. author = models.CharField(max_length=50)
  82. ...the statement ``Book.objects.all()`` will return all books in the database.
  83. You can override a ``Manager``\'s base ``QuerySet`` by overriding the
  84. ``Manager.get_query_set()`` method. ``get_query_set()`` should return a
  85. ``QuerySet`` with the properties you require.
  86. For example, the following model has *two* ``Manager``\s -- one that returns
  87. all objects, and one that returns only the books by Roald Dahl::
  88. # First, define the Manager subclass.
  89. class DahlBookManager(models.Manager):
  90. def get_query_set(self):
  91. return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
  92. # Then hook it into the Book model explicitly.
  93. class Book(models.Model):
  94. title = models.CharField(max_length=100)
  95. author = models.CharField(max_length=50)
  96. objects = models.Manager() # The default manager.
  97. dahl_objects = DahlBookManager() # The Dahl-specific manager.
  98. With this sample model, ``Book.objects.all()`` will return all books in the
  99. database, but ``Book.dahl_objects.all()`` will only return the ones written by
  100. Roald Dahl.
  101. Of course, because ``get_query_set()`` returns a ``QuerySet`` object, you can
  102. use ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it.
  103. So these statements are all legal::
  104. Book.dahl_objects.all()
  105. Book.dahl_objects.filter(title='Matilda')
  106. Book.dahl_objects.count()
  107. This example also pointed out another interesting technique: using multiple
  108. managers on the same model. You can attach as many ``Manager()`` instances to
  109. a model as you'd like. This is an easy way to define common "filters" for your
  110. models.
  111. For example::
  112. class MaleManager(models.Manager):
  113. def get_query_set(self):
  114. return super(MaleManager, self).get_query_set().filter(sex='M')
  115. class FemaleManager(models.Manager):
  116. def get_query_set(self):
  117. return super(FemaleManager, self).get_query_set().filter(sex='F')
  118. class Person(models.Model):
  119. first_name = models.CharField(max_length=50)
  120. last_name = models.CharField(max_length=50)
  121. sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
  122. people = models.Manager()
  123. men = MaleManager()
  124. women = FemaleManager()
  125. This example allows you to request ``Person.men.all()``, ``Person.women.all()``,
  126. and ``Person.people.all()``, yielding predictable results.
  127. If you use custom ``Manager`` objects, take note that the first
  128. ``Manager`` Django encounters (in the order in which they're defined
  129. in the model) has a special status. Django interprets this first
  130. ``Manager`` defined in a class as the "default" ``Manager``, and
  131. several parts of Django (though not the admin application) will use
  132. that ``Manager`` exclusively for that model. As a result, it's often a
  133. good idea to be careful in your choice of default manager, in order to
  134. avoid a situation where overriding of ``get_query_set()`` results in
  135. an inability to retrieve objects you'd like to work with.
  136. .. _managers-for-related-objects:
  137. Using managers for related object access
  138. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  139. By default, Django uses an instance of a "plain" manager class when accessing
  140. related objects (i.e. ``choice.poll``), not the default manager on the related
  141. object. This is because Django needs to be able to retrieve the related
  142. object, even if it would otherwise be filtered out (and hence be inaccessible)
  143. by the default manager.
  144. If the normal plain manager class (:class:`django.db.models.Manager`) is not
  145. appropriate for your circumstances, you can force Django to use the same class
  146. as the default manager for your model by setting the `use_for_related_fields`
  147. attribute on the manager class. This is documented fully below_.
  148. .. _below: manager-types_
  149. .. _custom-managers-and-inheritance:
  150. Custom managers and model inheritance
  151. -------------------------------------
  152. Class inheritance and model managers aren't quite a perfect match for each
  153. other. Managers are often specific to the classes they are defined on and
  154. inheriting them in subclasses isn't necessarily a good idea. Also, because the
  155. first manager declared is the *default manager*, it is important to allow that
  156. to be controlled. So here's how Django handles custom managers and
  157. :ref:`model inheritance <model-inheritance>`:
  158. 1. Managers defined on non-abstract base classes are *not* inherited by
  159. child classes. If you want to reuse a manager from a non-abstract base,
  160. redeclare it explicitly on the child class. These sorts of managers are
  161. likely to be fairly specific to the class they are defined on, so
  162. inheriting them can often lead to unexpected results (particularly as
  163. far as the default manager goes). Therefore, they aren't passed onto
  164. child classes.
  165. 2. Managers from abstract base classes are always inherited by the child
  166. class, using Python's normal name resolution order (names on the child
  167. class override all others; then come names on the first parent class,
  168. and so on). Abstract base classes are designed to capture information
  169. and behavior that is common to their child classes. Defining common
  170. managers is an appropriate part of this common information.
  171. 3. The default manager on a class is either the first manager declared on
  172. the class, if that exists, or the default manager of the first abstract
  173. base class in the parent hierarchy, if that exists. If no default
  174. manager is explicitly declared, Django's normal default manager is
  175. used.
  176. These rules provide the necessary flexibility if you want to install a
  177. collection of custom managers on a group of models, via an abstract base
  178. class, but still customize the default manager. For example, suppose you have
  179. this base class::
  180. class AbstractBase(models.Model):
  181. ...
  182. objects = CustomerManager()
  183. class Meta:
  184. abstract = True
  185. If you use this directly in a subclass, ``objects`` will be the default
  186. manager if you declare no managers in the base class::
  187. class ChildA(AbstractBase):
  188. ...
  189. # This class has CustomManager as the default manager.
  190. If you want to inherit from ``AbstractBase``, but provide a different default
  191. manager, you can provide the default manager on the child class::
  192. class ChildB(AbstractBase):
  193. ...
  194. # An explicit default manager.
  195. default_manager = OtherManager()
  196. Here, ``default_manager`` is the default. The ``objects`` manager is
  197. still available, since it's inherited. It just isn't used as the default.
  198. Finally for this example, suppose you want to add extra managers to the child
  199. class, but still use the default from ``AbstractBase``. You can't add the new
  200. manager directly in the child class, as that would override the default and you would
  201. have to also explicitly include all the managers from the abstract base class.
  202. The solution is to put the extra managers in another base class and introduce
  203. it into the inheritance hierarchy *after* the defaults::
  204. class ExtraManager(models.Model):
  205. extra_manager = OtherManager()
  206. class Meta:
  207. abstract = True
  208. class ChildC(AbstractBase, ExtraManager):
  209. ...
  210. # Default manager is CustomManager, but OtherManager is
  211. # also available via the "extra_manager" attribute.
  212. .. _manager-types:
  213. Controlling Automatic Manager Types
  214. ===================================
  215. This document has already mentioned a couple of places where Django creates a
  216. manager class for you: `default managers`_ and the "plain" manager used to
  217. `access related objects`_. There are other places in the implementation of
  218. Django where temporary plain managers are needed. Those automatically created
  219. managers will normally be instances of the :class:`django.db.models.Manager`
  220. class.
  221. .. _default managers: manager-names_
  222. .. _access related objects: managers-for-related-objects_
  223. Throughout this section, we will use the term "automatic manager" to mean a
  224. manager that Django creates for you -- either as a default manager on a model
  225. with no managers, or to use temporarily when accessing related objects.
  226. Sometimes this default class won't be the right choice. One example is in the
  227. `django.contrib.gis` application that ships with Django itself. All `gis`
  228. models must use a special manager class (``GeoManager``) because they need a
  229. special queryset (``GeoQuerySet``) to be used for interacting with the
  230. database. It turns out that models which require a special manager like this
  231. need to use the same manager class wherever an automatic manager is created.
  232. Django provides a way for custom manager developers to say that their manager
  233. class should be used for automatic managers whenever it is the default manager
  234. on a model. This is done by setting the ``use_for_related_fields`` attribute on
  235. the manager class::
  236. class MyManager(models.Manager):
  237. use_for_related_fields = True
  238. ...
  239. If this attribute is set on the *default* manager for a model (only the
  240. default manager is considered in these situations), Django will use that class
  241. whenever it needs to automatically create a manager for the class. Otherwise,
  242. it will use :class:`django.db.models.Manager`.
  243. .. admonition:: Historical Note
  244. Given the purpose for which it's used, the name of this attribute
  245. (``use_for_related_fields``) might seem a little odd. Originally, the
  246. attribute only controlled the type of manager used for related field
  247. access, which is where the name came from. As it became clear the concept
  248. was more broadly useful, the name hasn't been changed. This is primarily
  249. so that existing code will :ref:`continue to work <misc-api-stability>` in
  250. future Django versions.
  251. Writing Correct Managers For Use In Automatic Manager Instances
  252. ---------------------------------------------------------------
  253. As already suggested by the `django.contrib.gis` example, above, the
  254. ``use_for_related_fields`` feature is primarily for managers that need to
  255. return a custom ``QuerySet`` subclass. In providing this functionality in your
  256. manager, there are a couple of things to be remember and that's the topic of
  257. this section.
  258. Do not filter away any results in this type of manager subclass
  259. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  260. One reason an automatic manager is used is to access objects that are related
  261. to from some other model. In those situations, Django has to be able to see
  262. all the objects for the model it is fetching, so that *anything* which is
  263. referred to can be retrieved.
  264. If you override the ``get_query_set()`` method and filter out any rows, Django
  265. will return incorrect results. Don't do that. A manager that filters results
  266. in ``get_query_set()`` is not appropriate for use as an automatic manager.
  267. Set ``use_for_related_fields`` when you define the class
  268. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  269. The ``use_for_related_fields`` attribute must be set on the manager *class*,
  270. object not on an *instance* of the class. The earlier example shows the
  271. correct way to set it, whereas the following will not work::
  272. # BAD: Incorrect code
  273. class MyManager(models.Manager):
  274. ...
  275. # Sets the attribute on an instance of MyManager. Django will
  276. # ignore this setting.
  277. mgr = MyManager()
  278. mgr.use_for_related_fields = True
  279. class MyModel(models.Model):
  280. ...
  281. objects = mgr
  282. # End of incorrect code.
  283. You also shouldn't change the attribute on the class object after it has been
  284. used in a model, since the attribute's value is processed when the model class
  285. is created and not subsequently reread. Set the attribute on the manager class
  286. when it is first defined, as in the initial example of this section and
  287. everything will work smoothly.