Django F() division - How to avoid rounding off

后端 未结 4 1112
旧巷少年郎
旧巷少年郎 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:54

    Simply make use of F()'s support for multiplication to convert one factor to decimal number.

    Combined expression then would look like:

    from decimal import Decimal
    
    q = MyModel.objects.order_by('-value1').annotate(
                res=ExpressionWrapper(
                    (F('value1') * Decimal('1.0') / F('value2')), 
                    output_field=FloatField()),
                )
    

    I find this more elegant way then write raw SQL CAST on value1 field and then do the division.

提交回复
热议问题