Django F() division - How to avoid rounding off

后端 未结 4 1295
旧巷少年郎
旧巷少年郎 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 11:48

    Unfortunately the ORM F('value1') / F('value2') operation is executed on the database side, therefore if both fields declared as integer you will definitely get the integer result. In Django 1.11.7 you could simply cast one of the F() expression to decimal like this:

     qs = (
         MyModel.objects
         .annotate(
             res=ExpressionWrapper(
                 F('value1') * 1.0 / F('value2'), 
                 output_field=FloatField(),
             ),
         )
     )
    

提交回复
热议问题