Django admin change_list view get ChangeList queryset - better solution than my monkey patch
django, django-admin
Solution
I don't know if this answers to your question but the class `ChangeList` has an attribute called `query_set` (you can find the code here `https://github.com/django/django/blob/master/django/contrib/admin/views/main.py`) already containing the queryset.
BTW the `changelist_view()` function (source at `https://github.com/django/django/blob/master/django/contrib/admin/options.py`) returns a `TemplateResponse` (source at https://github.com/django/django/blob/master/django/template/response.py) that has a variable named `context_data` which points to the context. You can try to extend the content of this variable.
Below follows the untested code
class TicketAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
response = super(TicketAdmin, self).changelist_view(request, extra_context)
filtered_query_set = response.context_data["cl"].queryset
currencies_count = filtered_query_set.values('bookmaker__currency').distinct().count()
extra_context = {
'currencies_count': currencies_count,
}
response.context_data.update(extra_context)
return response
Problem
I need to get a changelist view queryset in django admin. Currently, I have this monkey patch which makes 4 extra queries, so I'm looking for a better solution. My point is: I want to pass some extra values to django admin change_list.html template which I get from creating queries. For those queries, I need the queryset which is used in django admin changelist view with request filters applied. This is the same data which I see filtered, ordered etc. I want to make graphs from this data. Do you understand me? Thanks ``` #admin.py from django.contrib.admin.views.main import ChangeList class TicketAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): 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) # 3 extra queries filtered_query_set = cl.get_query_set(request) # 1 extra query currencies_count = filtered_query_set.values('bookmaker__currency').distinct().count() extra_context = { 'currencies_count': currencies_count, } return super(TicketAdmin, self).changelist_view(request, extra_context=extra_context) ```