Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to filter a queryset in the django admin?

I'm trying to define an action for a model Bar -- but I only want the list of Bar objects related to a user Foo.

Before I start mucking around in the admin code and passing in a custom queryset (or writing a custom view that hijacks the admin's multi-checkbox support), I figured I'd check to see if there were a way I could slice up the data as is so I get a list view.

Note: I'm not trying to sort by related user, and I'm not trying to add extra options to the default list view to filter by user; I need a specific URL or view that will give me just a list of Bar objects to a specific user Foo.

like image 593
andrew Avatar asked Oct 30 '09 21:10

andrew


People also ask

Can I filter a Queryset Django?

With the Django QuerySet class, you can apply filters that return QuerySets defined by your filters. The filter() method returns all objects that match the keyword arguments given to the method.

What is list filter in Django admin?

Django allows the user of the admin site to filter the instances of a Model by adding the list_filter attribute to your ModelAdmin objects. You can find more information about the Django's filtering utilities in the official documentation, in the Django Admin Site section.


2 Answers

All you need to do is override the get_queryset() method on your ModelAdmin. Something like this:

class ThisAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        """
        Filter the objects displayed in the change_list to only
        display those for the currently signed in user.
        """
        qs = super(ThisAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(owner=request.user)

The advantage of this approach is that it doesn't clutter up your nice pretty admin URLs (and also, therefore, make it extremely obvious to your users how to view other people objects).

like image 191
Josh Ourisman Avatar answered Oct 29 '22 04:10

Josh Ourisman


It's not documented, but the standard changelist view accepts normal queryset filter parameters as GET arguments. So you can do:

/admin/myapp/bar/?user__username=foo
like image 27
Daniel Roseman Avatar answered Oct 29 '22 04:10

Daniel Roseman