Override default queryset in Django admin

Natan Yellin picture Natan Yellin · Sep 10, 2012 · Viewed 53.6k times · Source

One of my models has a deleted flag, which is used to hide objects globally:

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

How can I override the default queryset used by Django admin module to include deleted conversations?

Answer

Konrad Hałas picture Konrad Hałas · Sep 10, 2012

You can override get_queryset method in your model admin class.

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)

Note in Django<=1.5 the method was named just queryset.