10

我需要在 django admin 中获取更改列表视图查询集。目前,我有这个猴子补丁,它会进行 4 个额外的查询,所以我正在寻找更好的解决方案。

我的观点是:我想将一些额外的值传递给我从创建查询中获得的 django admin change_list.html 模板。对于这些查询,我需要在 django admin 更改列表视图中使用的查询集,并应用了请求过滤器。这是我看到过滤、排序等的相同数据。我想根据这些数据制作图表。

你了解我吗?谢谢

#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)
4

1 回答 1

18

我不知道这是否回答了您的问题,但是该类ChangeList有一个名为query_set(您可以在此处找到代码https://github.com/django/django/blob/master/django/contrib/admin/views/main.py)的属性,该属性已经包含查询集。

顺便说一句,changelist_view()函数 (source at https://github.com/django/django/blob/master/django/contrib/admin/options.py) 返回一个TemplateResponse (source at https://github.com/django/django/blob/master/django/template/response.pycontext_data ),它有一个指向上下文的变量。您可以尝试扩展此变量的内容。

下面是未经测试的代码

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
于 2012-12-30T01:20:25.487 回答