Managers

  • class Manager[源代码]
  • A Manager is the interface through which database query operations areprovided to Django models. At least one Manager exists for every model ina Django application.

The way Manager classes work is documented in 进行查询;this document specifically touches on model options that customize Managerbehavior.

Manager names

By default, Django adds a Manager with the name objects to every Djangomodel class. However, if you want to use objects as a field name, or if youwant to use a name other than objects for the Manager, you can renameit on a per-model basis. To rename the Manager for a given class, define aclass attribute of type models.Manager() on that model. For example:

  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. #...
  5. people = models.Manager()

Using this example model, Person.objects will generate anAttributeError exception, but Person.people.all() will provide a listof all Person objects.

Custom managers

You can use a custom Manager in a particular model by extending the baseManager class and instantiating your custom Manager in your model.

There are two reasons you might want to customize a Manager: to add extraManager methods, and/or to modify the initial QuerySet the Managerreturns.

Adding extra manager methods

Adding extra Manager methods is the preferred way to add "table-level"functionality to your models. (For "row-level" functionality — i.e., functionsthat act on a single instance of a model object — use Model methods, not custom Manager methods.)

A custom Manager method can return anything you want. It doesn't have toreturn a QuerySet.

For example, this custom Manager offers a method with_counts(), whichreturns a list of all OpinionPoll objects, each with an extranum_responses attribute that is the result of an aggregate query:

  1. from django.db import models
  2.  
  3. class PollManager(models.Manager):
  4. def with_counts(self):
  5. from django.db import connection
  6. with connection.cursor() as cursor:
  7. cursor.execute("""
  8. SELECT p.id, p.question, p.poll_date, COUNT(*)
  9. FROM polls_opinionpoll p, polls_response r
  10. WHERE p.id = r.poll_id
  11. GROUP BY p.id, p.question, p.poll_date
  12. ORDER BY p.poll_date DESC""")
  13. result_list = []
  14. for row in cursor.fetchall():
  15. p = self.model(id=row[0], question=row[1], poll_date=row[2])
  16. p.num_responses = row[3]
  17. result_list.append(p)
  18. return result_list
  19.  
  20. class OpinionPoll(models.Model):
  21. question = models.CharField(max_length=200)
  22. poll_date = models.DateField()
  23. objects = PollManager()
  24.  
  25. class Response(models.Model):
  26. poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)
  27. person_name = models.CharField(max_length=50)
  28. response = models.TextField()

With this example, you'd use OpinionPoll.objects.with_counts() to returnthat list of OpinionPoll objects with num_responses attributes.

Another thing to note about this example is that Manager methods canaccess self.model to get the model class to which they're attached.

Modifying a manager's initial QuerySet

A Manager’s base QuerySet returns all objects in the system. Forexample, using this model:

  1. from django.db import models
  2.  
  3. class Book(models.Model):
  4. title = models.CharField(max_length=100)
  5. author = models.CharField(max_length=50)

…the statement Book.objects.all() will return all books in the database.

You can override a Manager’s base QuerySet by overriding theManager.get_queryset() method. get_queryset() should return aQuerySet with the properties you require.

For example, the following model has two Managers — one that returnsall objects, and one that returns only the books by Roald Dahl:

  1. # First, define the Manager subclass.
  2. class DahlBookManager(models.Manager):
  3. def get_queryset(self):
  4. return super().get_queryset().filter(author='Roald Dahl')
  5.  
  6. # Then hook it into the Book model explicitly.
  7. class Book(models.Model):
  8. title = models.CharField(max_length=100)
  9. author = models.CharField(max_length=50)
  10.  
  11. objects = models.Manager() # The default manager.
  12. dahl_objects = DahlBookManager() # The Dahl-specific manager.

With this sample model, Book.objects.all() will return all books in thedatabase, but Book.dahl_objects.all() will only return the ones written byRoald Dahl.

Of course, because get_queryset() returns a QuerySet object, you canuse filter(), exclude() and all the other QuerySet methods on it.So these statements are all legal:

  1. Book.dahl_objects.all()
  2. Book.dahl_objects.filter(title='Matilda')
  3. Book.dahl_objects.count()

This example also pointed out another interesting technique: using multiplemanagers on the same model. You can attach as many Manager() instances toa model as you'd like. This is an easy way to define common "filters" for yourmodels.

例如:

  1. class AuthorManager(models.Manager):
  2. def get_queryset(self):
  3. return super().get_queryset().filter(role='A')
  4.  
  5. class EditorManager(models.Manager):
  6. def get_queryset(self):
  7. return super().get_queryset().filter(role='E')
  8.  
  9. class Person(models.Model):
  10. first_name = models.CharField(max_length=50)
  11. last_name = models.CharField(max_length=50)
  12. role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor'))))
  13. people = models.Manager()
  14. authors = AuthorManager()
  15. editors = EditorManager()

This example allows you to request Person.authors.all(), Person.editors.all(),and Person.people.all(), yielding predictable results.

Default managers

  • Model._default_manager
  • If you use custom Manager objects, take note that the first ManagerDjango encounters (in the order in which they're defined in the model) has aspecial status. Django interprets the first Manager defined in a class asthe "default" Manager, and several parts of Django (includingdumpdata) will use that Manager exclusively for that model. As aresult, it's a good idea to be careful in your choice of default manager inorder to avoid a situation where overriding get_queryset() results in aninability to retrieve objects you'd like to work with.

You can specify a custom default manager using Meta.default_manager_name.

If you're writing some code that must handle an unknown model, for example, ina third-party app that implements a generic view, use this manager (or_base_manager) rather than assuming the model has an objectsmanager.

Base managers

  • Model._base_manager

By default, Django uses an instance of the Model._base_manager managerclass when accessing related objects (i.e. choice.question), not the_default_manager on the related object. This is because Django needs to beable to retrieve the related object, even if it would otherwise be filtered out(and hence be inaccessible) by the default manager.

If the normal base manager class (django.db.models.Manager) isn'tappropriate for your circumstances, you can tell Django which class to use bysetting Meta.base_manager_name.

Base managers aren't used when querying on related models. For example, if theQuestion model from the tutorial had a deletedfield and a base manager that filters out instances with deleted=True, aqueryset like Choice.objects.filter(questionnamestartswith='What')would include choices related to deleted questions.

Don't filter away any results in this type of manager subclass

This manager is used to access objects that are related to from some othermodel. In those situations, Django has to be able to see all the objects forthe model it is fetching, so that anything which is referred to can beretrieved.

If you override the get_queryset() method and filter out any rows, Djangowill return incorrect results. Don't do that. A manager that filters resultsin get_queryset() is not appropriate for use as a base manager.

Calling custom QuerySet methods from the manager

While most methods from the standard QuerySet are accessible directly fromthe Manager, this is only the case for the extra methods defined on acustom QuerySet if you also implement them on the Manager:

  1. class PersonQuerySet(models.QuerySet):
  2. def authors(self):
  3. return self.filter(role='A')
  4.  
  5. def editors(self):
  6. return self.filter(role='E')
  7.  
  8. class PersonManager(models.Manager):
  9. def get_queryset(self):
  10. return PersonQuerySet(self.model, using=self._db)
  11.  
  12. def authors(self):
  13. return self.get_queryset().authors()
  14.  
  15. def editors(self):
  16. return self.get_queryset().editors()
  17.  
  18. class Person(models.Model):
  19. first_name = models.CharField(max_length=50)
  20. last_name = models.CharField(max_length=50)
  21. role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor'))))
  22. people = PersonManager()

This example allows you to call both authors() and editors() directly fromthe manager Person.people.

Creating a manager with QuerySet methods

In lieu of the above approach which requires duplicating methods on both theQuerySet and the Manager, QuerySet.as_manager() can be used to create an instanceof Manager with a copy of a custom QuerySet’s methods:

  1. class Person(models.Model):
  2. ...
  3. people = PersonQuerySet.as_manager()

The Manager instance created by QuerySet.as_manager() will be virtuallyidentical to the PersonManager from the previous example.

Not every QuerySet method makes sense at the Manager level; forinstance we intentionally prevent the QuerySet.delete() method from being copied ontothe Manager class.

Methods are copied according to the following rules:

  • Public methods are copied by default.
  • Private methods (starting with an underscore) are not copied by default.
  • Methods with a queryset_only attribute set to False are always copied.
  • Methods with a queryset_only attribute set to True are never copied.
    例如:
  1. class CustomQuerySet(models.QuerySet):
  2. # Available on both Manager and QuerySet.
  3. def public_method(self):
  4. return
  5.  
  6. # Available only on QuerySet.
  7. def _private_method(self):
  8. return
  9.  
  10. # Available only on QuerySet.
  11. def opted_out_public_method(self):
  12. return
  13. opted_out_public_method.queryset_only = True
  14.  
  15. # Available on both Manager and QuerySet.
  16. def _opted_in_private_method(self):
  17. return
  18. _opted_in_private_method.queryset_only = False

from_queryset()

  • classmethod fromqueryset(_queryset_class)
  • For advanced usage you might want both a custom Manager and a customQuerySet. You can do that by calling Manager.fromqueryset() whichreturns a _subclass of your base Manager with a copy of the customQuerySet methods:
  1. class BaseManager(models.Manager):
  2. def manager_only_method(self):
  3. return
  4.  
  5. class CustomQuerySet(models.QuerySet):
  6. def manager_and_queryset_method(self):
  7. return
  8.  
  9. class MyModel(models.Model):
  10. objects = BaseManager.from_queryset(CustomQuerySet)()

还可以将生成的类存储到变量中:

  1. CustomManager = BaseManager.from_queryset(CustomQuerySet)
  2.  
  3. class MyModel(models.Model):
  4. objects = CustomManager()

自定义管理器和模型继承

下面是Django如何处理自定义管理器和 model inheritance

  • 基类的管理者总是由子类继承,使用Python的正常名称解析顺序(子类上的名称覆盖所有其他类;然后在第一个父类上命名)等等。
  • 如果没有在模型和/或其父母上宣布管理人员,Django就会自动创建objects管理器。
  • 类上的默认管理器要么是使用:attr:Meta.default_manager_name ,要么是在模型上声明的第一个管理器,或者是第一个父模型的默认管理器。
    如果您想通过抽象基类在一组模型上安装自定义管理器集合,但仍然自定义默认管理器,则这些规则提供了必要的灵活性。
  1. class AbstractBase(models.Model):
  2. # ...
  3. objects = CustomManager()
  4.  
  5. class Meta:
  6. abstract = True

如果您在子类中直接使用这一点,如果您在基类中没有声明任何管理器,那么 objects 将是默认的管理器:

  1. class ChildA(AbstractBase):
  2. # ...
  3. # This class has CustomManager as the default manager.
  4. pass

如果您想从AbstractBase继承,但提供不同的默认管理器,则可以在子类上提供默认管理器:

  1. class ChildB(AbstractBase):
  2. # ...
  3. # An explicit default manager.
  4. default_manager = OtherManager()

在这里,default_manager是默认的。objects 管理器仍然可用,因为它是继承的。它只是没有被用作默认值。

最后,对于这个示例,假设您想要向子类中添加额外的管理器,但是仍然使用来自AbstractBase的默认管理器。您不能直接在子类中添加新的管理器,因为这将覆盖默认值,并且您还必须显式地包含来自抽象基类的所有管理器。解决方案是将额外的管理器放到另一个基类中,并在默认值之后将其引入继承层次结构:

  1. class ExtraManager(models.Model):
  2. extra_manager = OtherManager()
  3.  
  4. class Meta:
  5. abstract = True
  6.  
  7. class ChildC(AbstractBase, ExtraManager):
  8. # ...
  9. # Default manager is CustomManager, but OtherManager is
  10. # also available via the "extra_manager" attribute.
  11. pass

请注意,虽然可以在抽象模型上定义自定义管理器,但不能使用抽象模型调用*任何方法。即:

  1. ClassA.objects.do_something()

是合法的,但:

  1. AbstractBase.objects.do_something()

这将引起一个例外。这是因为管理人员打算封装管理对象集合的逻辑。因为您不能拥有抽象对象的集合,所以管理抽象对象是没有意义的。如果您有适用于抽象模型的功能,则应该将该功能放在抽象模型上的 静态方法类方法 中。

执行关系

无论您在自定义的 Manager 中添加了什么特性,都必须能够对 Manager 实例进行简单的复制;也就是说,以下代码必须有效:

  1. >>> import copy
  2. >>> manager = MyManager()
  3. >>> my_copy = copy.copy(manager)

Django在某些查询期间对管理器对象进行浅拷贝;如果您的管理器无法被复制,那么这些查询将失败。

This won't be an issue for most custom managers. If you are justadding simple methods to your Manager, it is unlikely that youwill inadvertently make instances of your Manager uncopyable.However, if you're overriding getattr or some other privatemethod of your Manager object that controls object state, youshould ensure that you don't affect the ability of your Manager tobe copied.