1

所以,我已经阅读了大部分文档,并且我一直在四处寻找,但我找不到我的问题的答案。我将从代码开始。

# Manager
class ActiveManager(models.Manager):
    def get_query_set(self):
        return super(ActiveManager, self).get_query_set().filter(is_active=True)
# Model
class ModelA(models.Model):
    # ...
    is_active = models.BooleanField()
    objects = ActiveManager()
    all_objects = models.Manager()

所以,当我在玩的时候,我注意到如果我这样写并使用get_object_or_404(),那么它将使用ActiveManager来首先搜索所有活动记录,然后返回与我的查询相关的记录。但是,如果我切换了经理的顺序:

class ModelA(models.Model):
    # ...
    all_objects = models.Manager()
    objects = ActiveManager()

然后它使用默认管理器(在这种情况下all_objects)进行查询。我想知道此更改会影响哪些其他功能。

编辑:我知道在类中找到的第一个管理器成为默认管理器,但我想知道哪些特定功能使用这个默认管理器(如get_object_or_404

4

2 回答 2

2

这是文档中的相关内容:“如果您使用自定义Manager对象,请注意第一个ManagerDjango 遇到(按照它们在模型中定义的顺序)具有特殊状态。Django 将Manager类中定义的第一个解释为"default" Manager,并且 Django 的几个部分(包括dumpdata)将Manager专门为该模型使用它。因此,在选择默认管理器时要小心,以避免覆盖get_query_set()导致无法使用的情况检索您想要使用的对象”

如果你看实现的方式get_object_or_404,他们使用_default_manager模型的属性,这就是 Django 遇到的第一个管理器是如何引用的。(据我所知,所有 Django 内部都是以这种方式工作的——它们从不使用Model.objects等,因为你不应该假设碰巧调用了默认管理器objects)。

于 2011-07-26T15:20:29.087 回答
0

它影响很多事情。管理器的默认名称 ,objects只是默认名称,但不是必需的。如果您没有包含objects在模型定义中并且只是将管理器定义为all_objectsModelA.objects则不会存在。如果模型上没有其他管理器并且您没有objects自己定义,Django 只会为其分配一个默认管理器。

Anyways, because of this Django takes the first manager defined in a model and calls that the "default", and later uses the "default" manager anytime is needs to reference the model's manager (because, again, it can't simply use objects because objects might not be defined).

The rule of thumb is that the standard manager that Django should use (in a sense, the manager that should most normally be used), should be the first one defined, whether it be assigned to objects or something else entirely. Every other additional manager should come after that.

于 2011-07-26T15:21:18.957 回答