Restrict django FloatField to 2 decimal places

前端 未结 3 654
予麋鹿
予麋鹿 2020-12-16 14:08

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.

I

3条回答
  •  我在风中等你
    2020-12-16 14:31

    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.

提交回复
热议问题