views:

642

answers:

2

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.

+9  A: 

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
Daniel Roseman
+3  A: 

If you're using 1.1.x it's actually extremely easy to pass in a custom queryset. All you need to do is override the queryset() method on your ModelAdmin. Something like this:

class ThisAdmin(admin.ModelAdmin):
    def 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).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(owner=request.user)

This can actually be done in the 1.0.x branch as well, but requires a little more extra code in your ModelAdmin.

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).

Josh Ourisman
This works fine for the models directly edited on the admin. How about the Foreign Keys that get auto populated in the drop downs.
Lakshman Prasad