在admin中添加额外的总行 - Django

时间:2018-02-14 14:12:12

标签: python django django-admin

应用的

admin.py是:

from django.contrib import admin
from django.db.models import Subquery, Sum, OuterRef

from .models import GoodsItem, FinishedGoodsItem, SoldGoodsItem

@admin.register(SoldGoodsItem)
class SoldGoodsItemAdmin(admin.ModelAdmin):
    fields = ('date', 'goods_item', 'weight')
    list_display = ('date', 'goods_item', 'weight')

@admin.register(FinishedGoodsItem)
class FinishedGoodsItemAdmin(admin.ModelAdmin):
    fields = ('date', 'goods_item', 'weight')
    list_display = ('date', 'goods_item', 'weight')

@admin.register(GoodsItem)
class GoodsItemAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'finished_good', 'sold_good', 'stock_available')

    def get_queryset(self, request):
        qs = super(GoodsItemAdmin, self).get_queryset(request)
        qs = qs.annotate(
            finished_good = Subquery(FinishedGoodsItem.objects.filter(goods_item=OuterRef('pk'))\
                .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]),
            sold_good = Subquery(SoldGoodsItem.objects.filter(goods_item=OuterRef('pk'))\
                .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1])
        )
        return qs

    def finished_good(self, obj):
        return obj.finished_good

    def sold_good(self, obj):
        return obj.sold_good

    def stock_available(self, obj):
        finished_good = 0 if self.finished_good(obj) is None else self.finished_good(obj)
        sold_good = 0 if self.sold_good(obj) is None else self.sold_good(obj)
        return '-' if (finished_good == 0 and sold_good == 0) else finished_good - sold_good

admin.site.site_header = 'Rajeshwari Steels'

对于GoodsItemAdmin,我想在记录表的底部显示一个额外的行。总行应显示所有三列的总计,即finished_goodsold_goodstock_available
这里使用GoodsItemAdmin中的方法显示所有三列,并通过覆盖get_queryset方法在queryset上进行注释。

我找到了this question,同时搜索了解决方案。该问题的答案建议覆盖管理员模板和changelist_view方法。

请帮我说明如何覆盖管理模板和changelist_view方法,以显示查询集上带注释列的总计行。
如果有任何其他好的解决方案,请告诉我。

0 个答案:

没有答案