Django Admin: Getting a QuerySet filtered according to GET string, exactly as seen in the change list?
In the Django admin, the user can set filters which limit the rows displayed in the change list. How can I get a QuerySet instance with filters set as defined by the query string? For instance, if I pass ?start_date_gte=2009-11-06, the Django admin will a开发者_如何学Gopply a qs.filter(start_date__gte...) somewhere. How can I access such a QuerySet?
I need this since obviously I don't want to rewrite the code that takes these GET parameters and filter()s a QuerySet accordingly.
Looks interesting. However, I was talking about using that QuerySet within the Admin. Found the answer, see below:
class MyAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
from django.contrib.admin.views.main import ChangeList
cl = ChangeList(request, self.model, self.list_display, self.list_display_links, self.list_filter, self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_editable, self)
# getting query set with same filters like current change list
filtered_query_set = cl.get_query_set()
Take a look at django-filter.
12 years later :) this right answer has some changes.
class MyAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
from django.contrib.admin.views.main import ChangeList
cl = ChangeList(
request,
self.model,
self.list_display,
self.list_display_links,
self.list_filter,
self.date_hierarchy,
self.search_fields,
self.list_select_related,
self.list_per_page,
self.list_max_show_all,
self.list_editable,
self,
self.sortable_by
)
# getting query set with same filters like current change list
filtered_query_set = cl.get_queryset(request)
精彩评论