将聚合表达式(Count/Count)结果除以zoro,无论如何

问题描述 投票:0回答:1

这是问题的代码片段


#multiplication works fine
drivers.annotate(
            completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) * Count('orders', distinct=True) ) * 100 ,
        )

#addition works fine
drivers.annotate(
            completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) + Count('orders', distinct=True) ) * 100 ,
        )

#subtraction works fine
drivers.annotate(
            completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) -  Count('orders', distinct=True) ) * 100 ,
        )

#diving not working (returns 0)
drivers.annotate(
            completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) / Count('orders', distinct=True) ) * 100 ,
        )

我在文档中找不到任何有用的东西,我认为这可能是由于返回类型所致,所以我尝试使用 output_field=FloatField() 将其包装在 ExeprisionWrapper 中,但仍然相同!

python-3.x django django-models
1个回答
0
投票

您正在执行整数除法,因此结果会被截断为零。

您可以将乘法移到前面,这样可以防止这种舍入错误:

drivers.annotate(
    completed_orders_percentage=100
    * Count('orders', filter=Q(orders__rejected=False), distinct=True)
    / Count('orders', distinct=True),
)
© www.soinside.com 2019 - 2024. All rights reserved.