django - annotate() - Sum() of a column with filter on another column

寵の児 提交于 2019-11-29 07:14:13

You could use conditional aggregation

queryset = queryset.annotate(
    stock_in_sum = Sum(Case(When(stock__ttype='I', then=F('stock__quantity')), output_field=DecimalField(), default=0)),
    stock_out_sum = Sum(Case(When(stock__ttype='O', then=F('stock__quantity')), output_field=DecimalField(), default=0)))
)

To make the sums, and after that compute the balance with F() expression

queryset = queryset.annotate(balance_stock=F('opening_stock') + F('stock_in_sum') - F('stock_out_sum'))

You can also chain the different operation instead of multiple assignations:

queryset = queryset.prefetch_related(...).annotate(...).annotate(...)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!