栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Multiple annotate with sum and display data in admin - Django

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Multiple annotate with sum and display data in admin - Django

This is known issue and occurs when we try to combine multiple aggregation, as
mentioned in
docs.

As a workaround for this particular problem, we can use Subquery expression.
Here is my updated admin.py using Subquery expression in

get_queryset
method
of
GoodsItemAdmin
.

from django.contrib import adminfrom django.db.models import Subquery, Sum, OuterReffrom .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

Hope someone finds this useful.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646653.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号