我有Django ORM queryset,我正在尝试执行以下操作
in_month = OrderEntry.objects.filter(order__closed_date__year=self.year).filter(
order__closed_date__month=month_nr)
result = in_month.values('product_code').annotate(
quantity=Sum('quantity'),
free_count=Sum('free_count'),
quantity_bottles=Sum(Case(
When(product_variant__megapack_quantity=4, then=(F('quantity') * Value(4))),
When(product_variant__megapack_quantity=None, then=F('quantity')),
default=Value(0),
output_field=IntegerField(),
))
)
但是,这不起作用。我收到的错误:
Cannot compute Sum('<Case: CASE WHEN <Q: (AND: ('product_variant__megapack_quantity', 4))> THEN <CombinedExpression: F(quantity) * Value(4)>, WHEN <Q: (AND: ('product_variant__megapack_quantity', None))> THEN F(quantity), ELSE Value(0)>'): '<Case: CASE WHEN <Q: (AND: ('product_variant__megapack_quantity', 4))> THEN <CombinedExpression: F(quantity) * Value(4)>, WHEN <Q: (AND: ('product_variant__megapack_quantity', None))> THEN F(quantity), ELSE Value(0)>' is an aggregate
我想实现的是一个包含4个字段的查询集: * 产品代码 *数量 * free_count *数量瓶
应按以下方式计算瓶数(用伪代码):
sum = 0
for order in orders:
if order.product_variant.megapack_quantity == 4:
sum += order.quantity * 4
else:
sum += order.quantity
如何使用Django ORM通过对数据库的单个查询来解决/实现它?