Math in Django ORM and SQLite: decimal ignored if round number, correct result if not round

In a complex query, I have an annotate like this one:

result.annotate(test=ExpressionWrapper(485.00 / F( 'period_duration' ), 
output_field=DecimalField()))

This gives me the correct result:

Decimal('8.01917989417989E-10')

However, if I replace 485.00 with 485:

result.annotate(test=ExpressionWrapper( 485 / F( 'period_duration' ),
output_field=DecimalField()))

I get:

Decimal('0')

This wouldn't be a problem, if it wasn't that 485 also comes from a field, called "value". My query looks like this:

result.annotate(test=ExpressionWrapper( F( 'value' ) / F( 'period_duration' ),
output_field=DecimalField()))

Value is a MoneyField, basically just a fancy wrapper around DecimalField.

I can force my users to always use proper decimals (485.00 as opposed to 485), which in itself would be bad design but... even then, if the database value is 485.00, Django behaves as if it is 485 and thus returns 0 while doing floating point math.

I have tried Casting value to a DecimalField, to no avail.

result.annotate( res=ExpressionWrapper(
Cast('value', output_field=DecimalField()) / F( 'period_duration' ),
output_field=DecimalField() )).last().res

Result is always:

Decimal('0')

Instead of the correct one:

Decimal('8.01917989417989E-10')

How can I force Django to always use floating point math?

p.s. period_duration is 604800000000, if it's of any help.

Are you sure F( 'value' ) is giving you a number?

MoneyField stores your attribute value in two columns, so F( 'value' ) might not be what you expect.

Maybe try F( 'value_amount' ).

Back to Top