Opened 10 years ago

Closed 10 years ago

#23320 closed Cleanup/optimization (invalid)

FloatField not converting values to float()

Reported by: Patrick Robetson Owned by: nobody
Component: Database layer (models, ORM) Version: 1.7-rc-2
Severity: Normal Keywords:
Cc: cmawebsite@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Baptiste Mispelon)

Apologies for creating an issue if this is the expected behaviour (FWIW there were no ideas on IRC):

Is the behaviour outlined in this snippet expected:

# models.py
from django.db import models
 
class Fl(models.Model):
    
    float = models.FloatField()
 
 
# ./manage.py shell
>>> from models import Fl
>>> a = Fl.objects.create(float=' 1.0 ')
>>> a
<Fl: Fl object>
>>> a.float
' 1.0 '

I'd have expected the FloatField to convert values to a float in the return object as well (I can verify that the to_python method is being run, because the number is saved to the database correctly.

Is the recommended way of solving this to subclass FloatField and use?

class MyFloatField(with_metaclass(models.SubBaseField, models.FloadField)):
   ...

Change History (3)

comment:1 by Collin Anderson, 10 years ago

Cc: cmawebsite@… added
Type: UncategorizedCleanup/optimization

This is consistent with most other fields.

Model(date='2010-01-01').date == '2010-01-01'
Model(decimal='0.1').decimal == '0.1'
Model(integer='6').integer == '6'

However, getting the data out of the database should work as expected:

Model.objects.get(id=Model.objects.create(float='0.6')).float == 0.6
Last edited 10 years ago by Collin Anderson (previous) (diff)

comment:2 by Baptiste Mispelon, 10 years ago

Description: modified (diff)

(pulled in the code from dpaste so that this report still makes sense in 4 weeks after the link expires)

comment:3 by Marc Tamlyn, 10 years ago

Resolution: invalid
Status: newclosed

This is consistent with other fields and is by design for performance reasons.

In essence you are doing the following:

>>> f = Fl()
>>> f.float = ' 0.6 '
>>> f.float
' 0.6 '

I don't find this behaviour particularly surprising, it would be more surprising if implicit casting was taking place.

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