Opened 4 years ago
Closed 4 years ago
#32761 closed Bug (duplicate)
Model meta field "to_python" behaviour with decimal fields
Reported by: | aiacamposm | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 3.2 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
When calling to_python
method of a model field I expect it returns the exact same value that will be stored in the database, i.e., when saved the instance and retrieved later, to have this same value as the corresponding attribute. However, it doesn't seem to behave correctly when the field is of type DecimalField.
I have a model MyModel
that has a field foo
with max_digits=10
and decimal_places=2
, so when I save a value 3.4211 (passed as a common float) the value stored is Decimal("3.42"). However, if call MyModel._meta.get_field("foo").to_python(3.4211)
the result is Decimal("3.421100000").
Inspecting the source code of this method to_python
I guess the problem is that it uses decimal.Context with prec
equal to the number of max_digits
, which is something that only makes sense if the number passed has max_digits
meaningful digits.
Should it be changed to return the decimal with the specified number of digits, or am I wrong assuming that to_python
should return the exact same value that will be stored?
Duplicate of #26459.