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

Paste-bin is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.