【问题标题】:saving a float to a FloatField Django model, why coercing to Unicode: need string or buffer, float found将浮点数保存到 FloatField Django 模型,为什么要强制使用 Unicode:需要字符串或缓冲区,找到浮点数
【发布时间】:2014-09-21 17:07:32
【问题描述】:

我有一个模型:

 class Conditions(models.Model):
        date_time = models.DateTimeField(blank=True, null=True)
        temperature = models.FloatField(blank=True, null=True)
        humidity = models.FloatField(blank=True, null=True)

        def __unicode__(self):
            return self.temperature

我有数据要加载到从谷歌文档导入的模型中。我保存的是这样的:

conditions_obj = Conditions.objects.get_or_create(
                    date_time=datetime.datetime.strptime(row[0],'%m/%d/%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S'),
                    temperature=float(row[1]),
                    humidity=float(row[2]))

当我这样做时,我得到了这个错误,我不确定为什么:

TypeError: coercing to Unicode: need string or buffer, float found

我的温度值是否需要保存为字符串,因为如果我这样做了,那么一切正常。只是看起来像集市。

【问题讨论】:

    标签: python django unicode


    【解决方案1】:

    问题不在于保存:问题在于您的__unicode__ 方法。顾名思义,它需要返回一个 unicode 值,而不是浮点数。

    你可以明确地转换它:

    def __unicode__(self):
        return unicode(self.temperature)
    

    【讨论】:

    • 我想我认为 __unicode__(self) 会返回 unicode 字符串。非常感谢!
    猜你喜欢
    • 2012-04-12
    • 2011-07-17
    • 2013-04-26
    • 1970-01-01
    • 2013-11-05
    • 2012-06-06
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多