Newtt
Newtt

Reputation: 6190

Cannot convert string to float inside Django Model

I've got a Django Model that has a field that saves as a string but has floating point values.

Ex: "0.123,0.221" is the string stored in the Location column. On saving, I want to save these values separately in latitude and longitude as floats. For this I've done the following to my model

class TestModel(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200)
    location = LocationField(blank=True, max_length=255)
    latitude = models.FloatField(editable=False, default=0.0)
    longitude = models.FloatField(editable=False, default=0.0)

    def __unicode__(self):
        return self.title

    def convert(s):
        try:
            return float(s)
        except ValueError:
            num, denom = s.split('/')
            return float(num) / float(denom)

    def save(self):
        if not self.id:
            a = self.location
            b = a.index(',')
            self.latitude = TestModel.convert(a[:b]) #Taking part of string before the comma
            self.longitude = TestModel.convert(a[b:]) #taking part of string after comma
        super(TestModel, self).save()

On saving, it gives me this error:

TypeError at /site/admin/MyApp/testmodel/add/
unbound method convert() must be called with TestModel instance as first argument (got unicode instance instead)

How do I solve this?

Upvotes: 2

Views: 758

Answers (1)

tttthomasssss
tttthomasssss

Reputation: 5971

First thing, your function needs the @staticmethod decorator if you want to use it in a static context:

@staticmethod
def convert(s):
    # Code here

Second thing, instead of playing with indices and slicing when splitting the location field it might be easier if you just use split(). See the difference below:

>>> a = '0.123,0.345'
>>> b = a.index(',')
>>> a[:b]
'0.123'
>>> a[b:]
',0.345' # <-- comma still exists here

Whereas if you use split(), the result looks like:

>>> arr = a.split(',')
>>> arr
['0.123', '0.345']
>>> arr[0]
'0.123'
>>> arr[1]
'0.345'

Upvotes: 3

Related Questions