2011-05-08 67 views
0

我想添加一個快捷方法來簡化我的數據輸出。我寫了下面的代碼(編輯不必要的位):使用模型方法輸入錯誤

address_line_one = models.CharField(max_length=100) 
address_line_two = models.CharField(max_length=100, blank=True) 
address_city = models.CharField(max_length=50) 
address_state = models.CharField(max_length=50) 
address_zip = models.IntegerField() 

def address(self): 
    return self.address_line_one+" "+self.address_line_two+" "+self.address_city+" "+self.address_state+" "+self.address_zip 

這很簡單。當我運行它時,出現以下錯誤:

Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "/srv/www/energy/energy/customers/models.py", line 83, in address 
    return self.address_line_two+" "+self.address_city+" "+self.address_state+" "+self.address_zip 
TypeError: coercing to Unicode: need string or buffer, long found 

爲什麼我得到此錯誤?

+1

如果廣告dress_zip是一個整數,不應該在連接它時將其轉換爲字符串嗎? str(self.address_zip) – 2011-05-08 20:07:19

+0

真的,但不是我的問題的根源(我試過刪除zip之前) – MrGlass 2011-05-08 20:11:31

+0

出於好奇,我決定嘗試「返回'測試'」,我仍然得到這個錯誤。我想我缺少一些方法所需的語法 – MrGlass 2011-05-08 20:15:57

回答

1

Python是強類型的。這意味着你不能連接一個int到一個字符串,而不顯式地轉換它。

幸運的是,有幾個快捷方式可以完成轉換,以及讓您的代碼更易於閱讀。

首先,你會發現自己串聯變量字符串文字的任何時候,你應該使用字符串格式化:

return "%s %s %s %s %s" % (self.address_line_one, 
          self.address_line_two, 
          self.address_city, 
          self.address_state 
          self.address_zip) 

你也可以使用字符串join方法,但是,你需要轉換的拉鍊整數明確:

return " ".join([self.address_line_one, 
       self.address_line_two, 
       self.address_city 
       self.address_state 
       unicode(self.address_zip)]) 
+0

感謝您的非常詳盡和寫得很好的答案。不幸的是,無論我在返程線上有什麼,我都會遇到錯誤。有沒有我缺少的一些Django語法? – MrGlass 2011-05-08 20:19:03

0

試試這個:

def address(self): 
    return " ".join([self.address_line_one, self.address_line_two, self.address_city, self.address_state, str(self.address_zip)])