Django - 指定Django管理员应该使用哪个模型管理员 [英] Django - specify which model manager Django admin should use
问题描述
我为Django模型创建了一个自定义管理器,该模型返回一个包含objects.all()的子集的QuerySet。我需要这个作为模型的默认管理器,因为我还创建一个自定义标签,它将从任何模型(由参数指定)检索内容,并且需要使用指定模型的默认管理器。除了 - Django管理员还使用此特定模型的默认管理器,这意味着并不是所有的模型实例都显示在管理员中。
I've created a custom Manager for a Django model which returns a QuerySet holding a subset of objects.all(). I need this to be the model's default Manager, since I am also creating a custom tag which will retrieve content from any model (specified by an argument), and needs to use the default Manager for the specified model. All that works fine, except - Django Admin is ALSO using the default Manager for this particular model, which means that not all model instances appear in the admin.
Django文档不要帮助:
The Django docs don't help:
如果您使用自定义管理对象,请注意,第一个经理Django遇到(在
中的顺序它们在模型中定义)具有特殊状态。 Django将此类中定义的第一个管理器解释为默认管理器,并且Django的几个部分(,而不是管理应用程序)将专门为该模型使用该Manager。
(Django Managers文档)
If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they're defined in the model) has a special status. Django interprets this first Manager defined in a class as the "default" Manager, and several parts of Django (though not the admin application) will use that Manager exclusively for that model. (Django Managers documentation)
管理员不应该使用默认管理器,但似乎在我的情况。请注意,我还明确添加了默认管理器对象
:
The admin isn't supposed to use the default Manager, but it seems to be in my case. Note that I have also explicitly add the default Manager objects
:
subset = CustomManager() # the default manager
objects = models.Manager() # the one I want admin to use
如何指定管理员应该使用哪个管理员?
How can I specify which Manager the admin should use?
推荐答案
您可以通过覆盖
def get_queryset(self, request):
# use our manager, rather than the default one
qs = self.model.objects.get_queryset()
# we need this from the superclass method
ordering = self.ordering or () # otherwise we might try to *None, which is bad ;)
if ordering:
qs = qs.order_by(*ordering)
return qs
这篇关于Django - 指定Django管理员应该使用哪个模型管理员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!