managers.txt 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 :ref:`topics-db-queries`; this
  11. document specifically touches on model options that customize ``Manager``
  12. behavior.
  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. class PollManager(models.Manager):
  47. def with_counts(self):
  48. from django.db import connection
  49. cursor = connection.cursor()
  50. cursor.execute("""
  51. SELECT p.id, p.question, p.poll_date, COUNT(*)
  52. FROM polls_opinionpoll p, polls_response r
  53. WHERE p.id = r.poll_id
  54. GROUP BY 1, 2, 3
  55. ORDER BY 3 DESC""")
  56. result_list = []
  57. for row in cursor.fetchall():
  58. p = self.model(id=row[0], question=row[1], poll_date=row[2])
  59. p.num_responses = row[3]
  60. result_list.append(p)
  61. return result_list
  62. class OpinionPoll(models.Model):
  63. question = models.CharField(max_length=200)
  64. poll_date = models.DateField()
  65. objects = PollManager()
  66. class Response(models.Model):
  67. poll = models.ForeignKey(Poll)
  68. person_name = models.CharField(max_length=50)
  69. response = models.TextField()
  70. With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return
  71. that list of ``OpinionPoll`` objects with ``num_responses`` attributes.
  72. Another thing to note about this example is that ``Manager`` methods can
  73. access ``self.model`` to get the model class to which they're attached.
  74. Modifying initial Manager QuerySets
  75. -----------------------------------
  76. A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
  77. example, using this model::
  78. class Book(models.Model):
  79. title = models.CharField(max_length=100)
  80. author = models.CharField(max_length=50)
  81. ...the statement ``Book.objects.all()`` will return all books in the database.
  82. You can override a ``Manager``\'s base ``QuerySet`` by overriding the
  83. ``Manager.get_query_set()`` method. ``get_query_set()`` should return a
  84. ``QuerySet`` with the properties you require.
  85. For example, the following model has *two* ``Manager``\s -- one that returns
  86. all objects, and one that returns only the books by Roald Dahl::
  87. # First, define the Manager subclass.
  88. class DahlBookManager(models.Manager):
  89. def get_query_set(self):
  90. return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
  91. # Then hook it into the Book model explicitly.
  92. class Book(models.Model):
  93. title = models.CharField(max_length=100)
  94. author = models.CharField(max_length=50)
  95. objects = models.Manager() # The default manager.
  96. dahl_objects = DahlBookManager() # The Dahl-specific manager.
  97. With this sample model, ``Book.objects.all()`` will return all books in the
  98. database, but ``Book.dahl_objects.all()`` will only return the ones written by
  99. Roald Dahl.
  100. Of course, because ``get_query_set()`` returns a ``QuerySet`` object, you can
  101. use ``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it.
  102. So these statements are all legal::
  103. Book.dahl_objects.all()
  104. Book.dahl_objects.filter(title='Matilda')
  105. Book.dahl_objects.count()
  106. This example also pointed out another interesting technique: using multiple
  107. managers on the same model. You can attach as many ``Manager()`` instances to
  108. a model as you'd like. This is an easy way to define common "filters" for your
  109. models.
  110. For example::
  111. class MaleManager(models.Manager):
  112. def get_query_set(self):
  113. return super(MaleManager, self).get_query_set().filter(sex='M')
  114. class FemaleManager(models.Manager):
  115. def get_query_set(self):
  116. return super(FemaleManager, self).get_query_set().filter(sex='F')
  117. class Person(models.Model):
  118. first_name = models.CharField(max_length=50)
  119. last_name = models.CharField(max_length=50)
  120. sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
  121. people = models.Manager()
  122. men = MaleManager()
  123. women = FemaleManager()
  124. This example allows you to request ``Person.men.all()``, ``Person.women.all()``,
  125. and ``Person.people.all()``, yielding predictable results.
  126. If you use custom ``Manager`` objects, take note that the first
  127. ``Manager`` Django encounters (in the order in which they're defined
  128. in the model) has a special status. Django interprets this first
  129. ``Manager`` defined in a class as the "default" ``Manager``, and
  130. several parts of Django (though not the admin application) will use
  131. that ``Manager`` exclusively for that model. As a result, it's often a
  132. good idea to be careful in your choice of default manager, in order to
  133. avoid a situation where overriding of ``get_query_set()`` results in
  134. an inability to retrieve objects you'd like to work with.
  135. Using managers for related object access
  136. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137. By default, Django uses a "bare" (i.e. default) manager when accessing related
  138. objects (i.e. ``choice.poll``). If this default isn't appropriate for your
  139. default manager, you can force Django to use a custom manager for related object
  140. attributes by giving it a ``use_for_related_fields`` property::
  141. class MyManager(models.Manager)::
  142. use_for_related_fields = True
  143. ...
  144. ...
  145. Custom managers and model inheritance
  146. -------------------------------------
  147. Class inheritance and model managers aren't quite a perfect match for each
  148. other. Managers are often specific to the classes they are defined on and
  149. inheriting them in subclasses isn't necessarily a good idea. Also, because the
  150. first manager declared is the *default manager*, it is important to allow that
  151. to be controlled. So here's how Django handles custom managers and
  152. :ref:`model inheritance <model-inheritance>`:
  153. 1. Managers defined on non-abstract base classes are *not* inherited by
  154. child classes. If you want to reuse a manager from a non-abstract base,
  155. redeclare it explicitly on the child class. These sorts of managers are
  156. likely to be fairly specific to the class they are defined on, so
  157. inheriting them can often lead to unexpected results (particularly as
  158. far as the default manager goes). Therefore, they aren't passed onto
  159. child classes.
  160. 2. Managers from abstract base classes are always inherited by the child
  161. class, using Python's normal name resolution order (names on the child
  162. class override all others; then come names on the first parent class,
  163. and so on). Abstract base classes are designed to capture information
  164. and behaviour that is common to their child classes. Defining common
  165. managers is an appropriate part of this common information.
  166. 3. The default manager on a class is either the first manager declared on
  167. the class, if that exists, or the default manager of the first abstract
  168. base class in the parent hierarchy, if that exists. If no default
  169. manager is explicitly declared, Django's normal default manager is
  170. used.