Django F()部门 - 如何避免四舍五入 [英] Django F() division - How to avoid rounding off

查看:254
本文介绍了Django F()部门 - 如何避免四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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

for i in q:                                          
    print(i.value1, i.value2, i.res)

所以,输出将是:

5 10 0.0
1 2 0.0

但我需要

5 10 0.5
1 2 0.5

Wy F()结果?如何不这样做?

Wy F() rounded the result? How not to do this?

谢谢!

推荐答案

您期望使用原始查询真的很容易实现,真的,我的意思是很难用纯django实现。

The result you are expecting is really easy to achieve with a raw query and really, I mean really hard to achieve with pure django.

from django.db.models import FloatField, ExpressionWrapper, F

template = '%(function)s(%(expressions)s AS FLOAT)'
fv1 =  Func(F('value1'), function='CAST', template=template)
fv2 =  Func(F('value2'), function='CAST', template=template)
ew = ExpressionWrapper(fv1/fv2, output_field = FloatField())


q = MyModel.objects.order_by('-value1').annotate(res = ew)

你不会指责这是优雅的,但它适用于Mysql和Postgresql。

You wouldn't accuse this of being elegant but it works on both Mysql and Postgresql.

提供一些背景舍入是由数据库完成的整数除法,因为你的字段是int。如果你想要小数除数,你需要将它们转换为小数。不幸的是,Django的投射不是很简单。

To provide some background. The rounding is done by the database doing integer division because the field you have are ints. If you want decimal division you need to cast them to decimals. Unfortunately casting is not very easy with Django.

Postgresql有一个非常优雅的方式来转换为浮动。 value1 :: float,但这不能从django内部使用(至少在我所知道的)

Postgresql has a really elegant way to cast to float. value1::float but this cannot be made use of from inside django (at least as far as I know)

这篇关于Django F()部门 - 如何避免四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆