一尘不染

覆盖Django管理中的默认查询集

django

我的一个模型具有一个delete标志,该标志用于全局隐藏对象:

class NondeletedManager(models.Manager):
    """Returns only objects which haven't been deleted"""

    def get_query_set(self):
        return super(NondeletedManager, self).get_query_set().exclude(deleted=True)

class Conversation(BaseModel):
    ...
    deleted = models.BooleanField(default=False)
    objects = NondeletedManager()
    all_conversations = models.Manager() # includes deleted conversations

如何覆盖Django管理模块使用的默认查询集以包括已删除的对话?


阅读 356

收藏
2020-03-27

共1个答案

一尘不染

你可以在模型管理类中重写 get_queryset方法。

class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(MyModelAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

请注意,在Django <= 1.5中,该方法被命名为just queryset

2020-03-27