Python 将 django FloatField 限制为 2 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23739030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:25:01  来源:igfitidea点击:

Restrict django FloatField to 2 decimal places

pythondjangoformsmodels

提问by Aidan Doherty

I am looking for a way to limit the FloatField in Django to 2 decimal places has anyone got a clue of how this could be done without having to use a DecimalField.

我正在寻找一种方法来将 Django 中的 FloatField 限制为 2 个小数位,有没有人知道如何在不使用 DecimalField 的情况下完成此操作。

I tried decimal_places=2but this was just giving me a migration error within the float field so i am thinking this method must only work within DecimalFields.

我试过了,decimal_places=2但这只是在浮点字段中给我一个迁移错误,所以我认为这个方法只能在 DecimalFields 中工作。

采纳答案by pcoronel

If you are only concerned with how your FloatFieldappears in forms, you can use the template filter floatformat.

如果您只关心您FloatField在表单中的显示方式,则可以使用模板过滤器floatformat

From the Django Docs:

来自 Django 文档:

If used with a numeric integer argument, floatformat rounds a number to that many decimal places.

如果与数字整数参数一起使用,则 floatformat 会将数字四舍五入到那么多小数位。

For example, if value = 34.23234, then in your template:

例如,如果 value = 34.23234,则在您的模板中:

{{ value|floatformat:2 }}  # outputs 34.23

回答by Catalin

Since Django 1.8+ you can use a custom validator for FloatField/or any ModelFields:

从 Django 1.8+ 开始,您可以为 FloatField/或任何 ModelField 使用自定义验证器:

def validate_decimals(value):
    try:
        return round(float(value), 2)
    except:
        raise ValidationError(
            _('%(value)s is not an integer or a float  number'),
            params={'value': value},
        )

...and in your model you can apply it like this:

...在您的模型中,您可以像这样应用它:

from django.db import models

class MyModel(models.Model):
    even_field = models.FloatField(validators=[validate_decimals])

回答by Colton Hicks

If you'd like to actually ensure that your model always gets saved with only two decimal places, rather than just changing the presentation of the model in a template, a custom save method on your model will work great. The example model below shows how.

如果您想真正确保您的模型始终只保存两位小数,而不是仅仅更改模板中模型的表示,那么模型上的自定义保存方法将非常有用。下面的示例模型显示了如何。

class MyDataModel(models.Model):
    my_float = models.FloatField()

    def save(self, *args, **kwargs):
        self.my_float = round(self.my_float, 2)
        super(MyDataModel, self).save(*args, **kwargs)

Now every time you save your model you will guarantee that the field will only be populated with a float of two decimal places. This can be generalized to rounding to any number of decimal places.

现在,每次保存模型时,您都将保证该字段将只填充两位小数的浮点数。这可以概括为四舍五入到任意数量的小数位。