[Django] #35821: Integer fields silently round floats

7 views
Skip to first unread message

Django

unread,
Oct 8, 2024, 8:19:14 PM10/8/24
to django-...@googlegroups.com
#35821: Integer fields silently round floats
----------------------------+-----------------------------------------
Reporter: Alex Krupp | Type: Bug
Status: new | Component: Uncategorized
Version: 5.1 | Severity: Normal
Keywords: | Triage Stage: Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
----------------------------+-----------------------------------------
I encountered a bug in my code today where I was trying to save 0.3 to a
PositiveSmallIntegerField with an initial default value of zero, and the
model kept showing zero even after saving it. This was super confusing
because it looked like the model just wasn't saving, until I eventually
realized that the value was being rounded.

Suggested improvements would be either:

1) Raise an error when attempting to save a non-Integer value
2) Update the documentation to specify that floats/decimals are rounded to
the nearest integer
--
Ticket URL: <https://code.djangoproject.com/ticket/35821>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
Oct 8, 2024, 8:47:51 PM10/8/24
to django-...@googlegroups.com
#35821: Integer fields silently round floats
-------------------------------+--------------------------------------
Reporter: Alex Krupp | Owner: (none)
Type: Bug | Status: closed
Component: Uncategorized | Version: 5.1
Severity: Normal | Resolution: invalid
Keywords: | Triage Stage: Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
-------------------------------+--------------------------------------
Changes (by Jacob Walls):

* resolution: => invalid
* status: new => closed

Comment:

Thanks for the ticket, but it sounds like `FloatField` may be more
appropriate for your use case. `IntegerField` is
[https://docs.djangoproject.com/en/5.1/ref/models/fields/#integerfield
documented] as representing integers, and since `int` and `float` are
distinct Python types, and throughout the documentation is the theme that
Django models coerce inputs to proper python types (sometimes implicitly,
elsewhere explicitly in the discussion of
[https://docs.djangoproject.com/en/5.1/ref/models/fields/#django.db.models.Field.to_python
to_python]), I think this behavior is sufficiently documented. Changing
the underlying behavior would introduce backwards compatibility concerns.
--
Ticket URL: <https://code.djangoproject.com/ticket/35821#comment:1>
Reply all
Reply to author
Forward
0 new messages