如何在Django项目中为DecimalFields设置全局舍入? [英] How to set global rounding for DecimalFields in Django project?
问题描述
我发现了与答案类似的问题,但在settings.py和在apps.py中设置getcontext()不起作用。标准的小数舍入是ROUND_HALF_EVEN,但是我需要设置ROUND_HALF_UP。
I found similar question with answers, but "setting the option in the settings.py" and "setting getcontext() in apps.py" doesn't work. Standard decimal rounding is ROUND_HALF_EVEN, but I need to set ROUND_HALF_UP.
我用引号重复我的问题-在Django应用程序中必须设置舍入选项的位置,以便它可以在项目中全局工作?
And I repeat my question with a quote - "where in the Django application I have to set rounding option, so that it would work globally in the project?"
推荐答案
对于Django项目,可以设置decimal.DefaultContext( py3 , py2 )。
For django project can work setting decimal.DefaultContext (py3, py2).
此上下文在多线程环境中最有用。
This context is most useful in multi-threaded environments.
这是我的代码,来自 settings.py
:
import decimal
# Set global decimal rounding to ROUND_HALF_UP (instead of ROUND_HALF_EVEN).
project_context = decimal.getcontext()
project_context.rounding = decimal.ROUND_HALF_UP
decimal.DefaultContext = project_context
这篇关于如何在Django项目中为DecimalFields设置全局舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!