1024programmer Java Why does Django decimal max_digits validation fail with strange behavior?

Why does Django decimal max_digits validation fail with strange behavior?

I have a model field full_time_equivalent:

full_time_equivalent = models.DecimalField(
     max_digits=5,
     decimal_places=2,
     default=100,
     validators=[
         MinValueValidator(Decimal(0)),
         MaxValueValidator(Decimal(100))
     ]
 )
 

To make sure the validator fires, I override save with the following command:

def save(self, *args, **kwargs):
     # Run validations
     self.full_clean()
     return super().save(*args, **kwargs)
 

Passed the following tests:

 project2_membership = ProjectMembership(
         user=self.new_user,
         project=project2,
         is_project_manager=False,
         full_time_equivalent=10.01
     )
 

When I enter validation, the following values ​​and corresponding errors are displayed:

Decimal('10.0099999999999997868371792719699442386627197265625')


 django.core.exceptions.ValidationError:
 {'full_time_equivalent': ['Ensure that there are no more than 5 digits in total.']
 

What did I do wrong?

1> Alasdair..:


The decimal value 10.01 cannot be fully represented as a floating point number. When converting the value to a decimal number, you end up with Decimal('10.0099999999999997868371792719699442386627197265625'), which is almost equal to Decimal('10.01'), but max_digits verification failed.

You can prevent the error by using the string '10.01' or the decimal Decimal('10.01') in your test.

from decimal import Decimal

 project2_membership = ProjectMembership(
     user=self.new_user,
     project=project2,
     is_project_manager=False,
     full_time_equivalent=Decimal('10.01')
 )
 

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/770710

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索