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

后端 未结 2 1852
再見小時候
再見小時候 2020-12-08 16:14

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

相关标签:
2条回答
  • 2020-12-08 16:34

    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
    
    0 讨论(0)
  • 2020-12-08 16:41

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

    0 讨论(0)
提交回复
热议问题