Luk*_*vic 6 django django-admin
我需要在django admin中获取changelist视图查询集.目前,我有这个猴子补丁,它提出了4个额外的查询,所以我正在寻找更好的解决方案.
我的观点是:我想将一些额外的值传递给django admin change_list.html模板,这是我从创建查询中得到的.对于那些查询,我需要在django管理员更改列表视图中使用的查询集,其中应用了请求过滤器.这是我看到的过滤,订购等相同的数据.我想根据这些数据制作图表.
你了解我吗?谢谢
#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)
Run Code Online (Sandbox Code Playgroud)
gip*_*ipi 13
我不知道这是否能回答你的问题,但该类ChangeList有一个名为query_set(你可以在这里找到代码https://github.com/django/django/blob/master/django/contrib/admin/views/main.py)的属性已经包含了查询集.
BTW changelist_view()函数(source at https://github.com/django/django/blob/master/django/contrib/admin/options.py)返回一个TemplateResponse (来自https://github.com/django/django/blob/master/django/template/response.py),它有一个context_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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8660 次 |
| 最近记录: |