【问题标题】:django: coercing to Unicode: need string or buffer, int founddjango:强制转换为 Unicode:需要字符串或缓冲区,找到 int
【发布时间】:2011-07-17 18:05:48
【问题描述】:

我在尝试对两个 int 值求和时遇到此错误:

if dups.count() > 0:
        for item in dups:
            pi.quantity = pi.quantity+item.quantity

pi 和 dups 都是同一模型的实例:

class PurchaseItem(models.Model):
    picture = models.ForeignKey(Picture, null=False)
    paperType = models.ForeignKey(paperType, null=False)
    printSize = models.ForeignKey(printSize, null=False)
    quantity = models.IntegerField(default=1, validators=[validators.MinValueValidator(1)])
    price = models.DecimalField(decimal_places=2,max_digits=8)
    dateCreated = models.DateTimeField(null=False)
    sessionKey = models.ForeignKey(Session, to_field="session_key", null=False)
    user = models.ForeignKey(User,null=True)

    def __unicode__(self):
        return self.id 

为什么 int 不够好?

如果我用 str() 包装值或使用它们的 .str() 表示,它并不能完全满足我的需要。 1 和 1 将在 11 之前而不是 2。

【问题讨论】:

  • request.GET 是否提交了这些值之一?如果是这样,来自 get dict 的所有项目都是字符串,您将不得不将其显式转换为 int。 ftr request.POST 做同样的事情。

标签: django math unicode model


【解决方案1】:

显然,item.quantity 是一个整数,pi.quantity 是 unicode。

我猜pi.quantity 之前被分配了一个字符串(django 将在数据库保存时转换),但在您再次实例化该类之前它不会返回强制值。该值根据某些 shell 会话进行缓存。

只需执行pi.quantity = int(pi.quantity) + item.quantity 或查看pi.quantity 的定义位置并改用整数!

【讨论】:

    【解决方案2】:

    您的代码: def unicode(自我): 返回 self.id

    应该是: def unicode(自我): 返回 unicode(self.id)

    【讨论】:

      【解决方案3】:

      你试过了吗

      if dups.count() > 0:
          for item in dups:
              pi.quantity = pi.quantity.to_python()+item.quantity.to_python()
      

      这可能会引发相同的错误,但值得一试。另一个(可怕的可怕)选项是执行以下操作:

      if dups.count() > 0:
          for item in dups:
              pi.quantity = int(str(pi.quantity))+int(str(item.quantity))
      

      但除非万不得已,否则不应该这样做,即使那样仍然不这样做,因为它掩盖了可能会在未来进一步导致更严重问题的实际问题。

      是否有可能发布完整的堆栈跟踪?

      【讨论】:

      • to_python() throws 'unicode' object has no attribute 'to_python'
      【解决方案4】:

      只需更改最后一行

      来自

      return self.id

      return str(self.id)

      【讨论】:

        猜你喜欢
        • 2015-02-01
        • 2012-04-12
        • 2013-04-26
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 2016-04-28
        • 2013-11-05
        • 2014-02-22
        相关资源
        最近更新 更多