Django F() division - How to avoid rounding off

后端 未结 4 1102
旧巷少年郎
旧巷少年郎 2021-02-19 11:30

I have this code:

q = MyModel.objects.order_by(\'-value1\').annotate(
            res=ExpressionWrapper(
                (F(\'value1\') / F(\'value2\')), 
               


        
4条回答
  •  盖世英雄少女心
    2021-02-19 12:04

    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.

提交回复
热议问题