首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向Django Admin添加字段总和的行

向Django Admin添加字段总和的行
EN

Stack Overflow用户
提问于 2015-03-16 02:54:02
回答 1查看 2.2K关注 0票数 0

我有一个发票应用程序,我希望能够在底部的管理面板中显示发票的总额。(我使用的是Django-suit)

在Django中有没有一种简单的方法来做到这一点?

e:像这样的东西应该起作用吗?

代码语言:javascript
复制
class InvoiceAdmin(admin.ModelAdmin):
    inlines = [InvoiceItemInline]
    list_display = ('description', 'date', 'status', 'invoice_amount')

    def invoice_amount(self, request):
        amount = InvoiceItem.objects.filter(invoice__id=request.id).values_list('price', flat=True)
        quantity = InvoiceItem.objects.filter(invoice__id=request.id).values_list('quantity', flat=True)
        total_current = amount(float) * quantity(float)
        total_amount = sum(total_current)
        return total_amount
EN

回答 1

Stack Overflow用户

发布于 2015-03-16 03:51:53

除了list_display仅适用于列出所有发票的页面之外,您的思路是正确的,在编辑特定发票时,您将看不到这一点

要在编辑特定发票时查看它,我认为您需要覆盖change_view方法,该方法被称为视图函数:

https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.change_view

如下所示:

代码语言:javascript
复制
class InvoiceAdmin(admin.ModelAdmin):
    inlines = [InvoiceItemInline]
    list_display = ('description', 'date', 'status', 'invoice_amount')

    # You need to customise the template to make use of the new context var
    change_form_template = 'admin/myapp/extras/mymodelname_change_form.html'

    def _invoice_amount(self, invoice_id):
        # define our own method to serve both cases
        order_values = InvoiceItem.objects.filter(invoice__id=invoice_id).values_list(
            'price', 'quantity', flat=True)
        return reduce(
            lambda total, (price, qty): total + (price * qty),
            order_values,
            0
        )

    def invoice_amount(self, instance):
        # provides order totals for invoices list view
        return self._invoice_amount(instance.pk)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        # provides order total on invoice change view
        extra_context = extra_context or {}
        extra_context['order_total'] = self._invoice_amount(object_id)
        return super(MyModelAdmin, self).change_view(request, object_id,
            form_url, extra_context=extra_context)

注意,您还需要覆盖变更表单模板,以利用我们在extra_context中传回的order_total变量

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29064787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档