I have this code:
q = MyModel.objects.order_by(\'-value1\').annotate(
res=ExpressionWrapper(
(F(\'value1\') / F(\'value2\')),
In v1.10, Django introduced a Cast function which makes this (almost) a breeze – the qualification being that you either need two casts or need to wrap the whole thing in an ExpressionWrapper to avoid a FieldError: Expression contains mixed types. You must set output_field.
q = MyModel.objects.annotate(
res=ExpressionWrapper(
(Cast('value1', FloatField()) / F('value2')),
output_field=FloatField()),
)
This is functionally equivalent to multiplying the enumerator by 1.0
, but an explicit cast makes your intention clearer than a multiplication by a number.