#14659 closed (invalid)
Assigning floats to DecimalFields
| Reported by: | Miguel Araujo | Owned by: | Miguel Araujo |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | dev |
| Severity: | Keywords: | DecimalField, float | |
| Cc: | muchochini@… | Triage Stage: | Unreviewed |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
DecimalField does not accept a float as a parameter, as it should be first converted to a string. So if you have DecimalField in a model, you will not be able to assign a float to it.
class Item(models.Model):
weight = models.DecimalField(max_digits=7, decimal_places = 2)
Item.objects.create(weight=100.43)
The patch passes Django tests, regards
Miguel Araujo
Attachments (1)
Change History (3)
by , 15 years ago
| Attachment: | DecimalField-accepting-floats-with-dots.patch added |
|---|
comment:1 by , 15 years ago
| Resolution: | → invalid |
|---|---|
| Status: | new → closed |
This follows the same rule as the stdlib Decimal class:
>>> from decimal import Decimal
>>> Decimal(100.43)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/decimal.py", line 649, in __new__
"First convert the float to a string")
TypeError: Cannot convert float to Decimal. First convert the float to a string
This rule is explicitly there to avoid nasty and hard to debug bugs: the 100.43 you write in the code is not actually 100.43 (but a very close float value), so you could end up passing a value which is not the one the code leads you to believe. So enforcing the conversion to be explicit is safer.
Patch