Search code examples
python-3.xdjangodjango-models

dividing aggregate expressions (Count / Count) results to zoro, no matter what


here's a code snippet of the problem


#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 ,
        )

i couldnt find anything useful in the docs, i thought that it might be due to type of the return so i tried to wrappe it in ExeprisionWrapper with output_field=FloatField() but still the same!


Solution

  • You are performing integer division, so the result gets truncated towards zero.

    You can move the multiplication to the front, which will thus prevent such rounding error:

    drivers.annotate(
        completed_orders_percentage=100
        * Count('orders', filter=Q(orders__rejected=False), distinct=True)
        / Count('orders', distinct=True),
    )