使用模型方法键入错误

时间:2011-05-08 20:00:32

标签: python django django-models

我正在尝试添加一种快捷方法来简化我的数据输出。我编写了以下代码(不必要的位编辑):

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

为什么我收到此错误?

2 个答案:

答案 0 :(得分: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方法,但为此您需要明确转换zip整数:

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

答案 1 :(得分:0)

试试这个:

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