这是问题的代码片段
#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 中,但仍然相同!
您正在执行整数除法,因此结果会被截断为零。
您可以将乘法移到前面,这样可以防止这种舍入错误:
drivers.annotate(
completed_orders_percentage=100
* Count('orders', filter=Q(orders__rejected=False), distinct=True)
/ Count('orders', distinct=True),
)