Categories
Python Answers

How to override default queryset in Python Django admin?

Spread the love

To override default queryset in Python Django admin, we can override the get_queryset method in our model.

For instance, we write

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)

to add the get_queryset into MyModelAdmin.

In it, we call call the super constructor with MyModelAdmin and self.

And we get the queryset wirth get_queryset from the super class.

And then we return the queryset we want according to the value of request.user.is_superuser.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *