【问题标题】:Adding a row for the sum of a field to Django Admin向 Django Admin 添加字段总和的行
【发布时间】:2015-03-15 18:54:02
【问题描述】:

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

在 Django 中是否有一种简单的方法可以做到这一点?

e:这样的事情应该工作吗?

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

【问题讨论】:

    标签: django django-models django-suit


    【解决方案1】:

    除了list_display 仅适用于列出所有发票的页面之外,您在正确的轨道上,在编辑特定发票时您不会看到

    要在编辑特定发票时查看它,我认为您需要覆盖 change_view 方法,该方法被称为视图函数:
    https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.change_view

    类似这样的:

    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 变量

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-30
      • 2011-09-23
      • 2015-01-24
      • 2018-03-05
      • 2014-06-18
      • 2014-09-04
      相关资源
      最近更新 更多