2014-09-03 46 views
1

我有一個Django模型,該字段的字段保存爲字符串,但具有浮點值。無法將字符串轉換爲Django模型中的浮點數

例如:"0.123,0.221"是存儲在Location列中的字符串。在保存時,我想將這些值分別保存爲浮點數latitudelongitude。爲此,我已經做了以下我的模型

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() 

節約,它給了我這個錯誤:

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

如何解決這個問題?

回答

3

的第一件事情,你的函數需要@staticmethod裝飾,如果你想在靜態情況下使用它:

@staticmethod 
def convert(s): 
    # Code here 

第二件事,而不是用索引和切片分割location場時,它可能會更容易打如果你只是使用split()。請參見下面的區別:

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

而如果你使用split(),結果是這樣的:

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