Opened 7 years ago

Closed 7 years ago

#19565 closed Bug (invalid)

FloatField object returns string when it's value is set from string

Reported by: jarek@… Owned by: nobody
Component: Uncategorized Version: 1.4
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


When float field is set from string value representing float, it is correctly saved (string is converted to float). But the field itself returns string in this case (even after save). This is pretty awful, because there is no error when the field is saved... and then suddenly you get a string value from field that you expect to return float. If you get access to the same row via different row, it - correctly - returns float instead.

Expected behaviour - the field should consistently return float.

Some code presenting it. I am als attaching .zipped full django project with only this model and test.

class TestModel(models.Model):

test_field = FloatField(null=True)


class TestFloatFieldAsString(TestCase):

def test_float_field_as_string(self):

model1 = TestModel(test_field=12.4)
print model1.test_field + 1.0

model2 = TestModel(test_field='12.4')

print model2.test_field + 1.0"Expect failure here")

except TypeError as exc:

print "expected:" + str(exc)

model3 = TestModel.objects.get(id =
print model3.test_field + 1.0

Attachments (1) (17.0 KB) - added by jarek@… 7 years ago.
full django project with test that shows the problem

Download all attachments as: .zip

Change History (5)

Changed 7 years ago by jarek@…

Attachment: added

full django project with test that shows the problem

comment:1 Changed 7 years ago by anonymous

The above test prints:

expected:cannot concatenate 'str' and 'float' objects

comment:2 Changed 7 years ago by anonymous

Also interesting effect is having 13.5 returned where we expect 13.4 .. but this one is likely caused by float precision arithmetics

comment:3 Changed 7 years ago by psjinx@…

If I call clean_fields() then m.test_field returns a float value, however if I call then m.test_field returns a string. It means clean_fields() method is not called while saving.

In [14]: m = TestModel(test_field='12.4')

In [15]: m.clean_fields() 

In [16]: m.test_field
Out[16]: 12.4

In [17]: m = TestModel(test_field='12.4')

In [18]:

In [19]: m.test_field
Out[19]: '12.4'

comment:4 Changed 7 years ago by Karen Tracey

Resolution: invalid
Status: newclosed

This is much like #12401, only for a different type of field. When a model object is created, the field value isn't converted from string (or whatever is passed in the constructor) to "correct" type for the field. As noted in, this is a long-standing design decision and cannot be changed at this point without significant backward incompatibility.

Note: See TracTickets for help on using tickets.
Back to Top