django-admin:添加带有总数的额外行 [英] django-admin: Add extra row with totals
问题描述
我使用标准的 django 管理模块来显示行列表.其中一列是数字字段.我想显示一个额外的总计"行,该行的大部分列都为空白,但数字列除外,该列应该是所有对象的总计.
I'm using the standard django admin module to display a list of rows. One of the columns is a numerical field. I'd like to display an extra 'totals' row that has most of the columns as blank, except for the numerical column, which should be the total for all of the objects.
在管理模块中是否有一种简单的方法可以做到这一点,或者我最好为它制作一个自定义视图?
Is there a simple way to do this within the admin module, or am I better off making a custom view for it?
我使用的是 Django 1.2.
I'm using Django 1.2.
推荐答案
是的,您可以通过多种方式来实现,但大多数 django-ist 的方式是:
Yes, you can do it in many ways, but most django-ist way to do is:
首先覆盖默认的django列表视图...并给出一个新的模板文件目录
First override the default django listing view... And give a new template file directory
ModelAdmin.changelist_view(self, request, extra_context=None)
喜欢:
class MyModelAdmin(admin.ModelAdmin):
# A template for a very customized change view:
change_list_template = 'admin/myapp/extras/sometemplate_change_form.html'
def get_total(self):
#functions to calculate whatever you want...
total = YourModel.objects.all().aggregate(tot=Sum('total'))['tot']
return total
def changelist_view(self, request, extra_context=None):
my_context = {
'total': self.get_total(),
}
return super(MyModelAdmin, self).changelist_view(request,
extra_context=my_context)
因此,您将列表视图上下文添加为总计",以保留您的总价值并将其传递给模板.
So, you add your list view context a 'total' that keeps your total value and pass it to the template.
如果 change_list_template 将设置,django 使用该模板,否则,它使用标准 django 模板.
if change_list_template will set, django uses that template, otherwise, it uses standard django template.
如果 def changelist_view(self, request, extra_context=None) 被调用,django 使用该函数来创建内容,否则使用默认的 django 视图.
If def changelist_view(self, request, extra_context=None) is called, django uses that function to create the content, otherwise it uses default django views.
然后创建一个 admin/myapp/extras/sometemplate_change_form.html
文件并将您的 {{total}}
放在您想要的任何位置.
Then create a admin/myapp/extras/sometemplate_change_form.html
file and place your {{total}}
to any place you want.
更新:我添加了一个简单的 aggregate
来计算总数.您可以编辑它以根据需要进行设置.
UPDATE: I add a simple aggregate
to calculate total. you can edit it to set it as your needs.
UPDATE 2:ModelAdmin 模板覆盖选项从 ModelAdmin.change_form_template
固定到 ModelAdmin.change_list_template
.(谢谢 c4urself).是的,但是更改默认的 django 管理模板是一个非常糟糕的选择,因为它被许多其他 ModelAdmin 使用,如果更新相关模板可能会导致问题.
UPDATE 2: ModelAdmin template override option fixed from ModelAdmin.change_form_template
to ModelAdmin.change_list_template
. (thank you c4urself). Yes, but changing the default django admin template is a really bad choice, since it is used by many other ModelAdmin's and it might cause problems if related templates are updated.
注意:
使用过滤器时,总数不会改变,请参阅下面的评论.
NB:
The Total doesn't change when using filters, see comment below.
这篇关于django-admin:添加带有总数的额外行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!