[英]Adding a row for the sum of a field to Django Admin
我有一個發票應用程序,我希望能夠在底部的管理面板中顯示發票的總額。 (我正在使用Django-suit)
在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
您處在正確的軌道上,只是list_display
僅適用於列出所有發票的頁面,在編輯特定發票時看不到
為了在編輯特定發票時看到它,我認為您需要重寫change_view
方法,該方法稱為視圖函數:
https://docs.djangoproject.com/zh-CN/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
變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.