English 中文(简体)
Django 跟踪碎片的最佳做法:前线或背后?
原标题:Django best practice to round decimals: frontend or backend?

我有一个范围相当广的Django站点,处理货币数额问题,需要用2个小数点显示,但由于在幕后就这些数额进行了数学操作,因此使用了4个小数点。 一些网页通过美国宇宙航空研究开发机构电话(作为JSON)和其他页面通过标准观点=1>获得这些数量;模板变量通过。 我的模型使用models.Decimal Field(max_datas=10, decimal_places=4,ail=Decimal(0)

现在,这个网站已经很庞大,我需要拿出一致的方法来处理这一恶性交集,但无论我怎么做,这似乎都很麻烦。 在这方面,我可以想到两种方式,但每种方法似乎并不理想。

  1. 前线:观点没有改变,有4个地方。 模板使用<代码>floatformat:2 过滤器和JS功能使用toFixed(2)转换新列入的JSON数据。 问题:需要在许多地方处理模板代码中的圆环。 JS Code.

  2. 背后:意见四舍五入到2处,并作为示例通过。 同样,对美国宇宙航空研究开发机构电话将所有精度提高到2个。 问题:目前的意见是处理格式格式而不是模板,在模板中不能以不同的方式编排特殊案件。

是否有处理Decimal 圆环的“proper, Djangonic”办法?

问题回答

考虑到这纯粹是一个介绍问题,我本能保留在模板中。 尽管如此,模板should尽可能繁琐,而且你可能不想把你的精子算成你在模板上的灵敏数字。

我也许会做以下事情:

  • Don t process any decimal place stuff in your views, unless it s part of your calculation logic.
  • Write a custom template filter that formats your floats based on parameters defined in your settings.py
  • Write a custom JavaScript function that does the same
  • Use your new filter and function to manipulate decimals as they appear in templates and AJAX callbacks.

这样,你就把你的介绍逻辑保留在模板一级,但你仍然坚持国家统一原则。 这仍然意味着贵方模板和 Java本有许多ed子,但我确实可以想到任何更清洁的方法,不陷入真正的黑城。





相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签