Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
django:强制使用Unicode:需要字符串或缓冲区,找到int_Django_Math_Unicode_Model - Fatal编程技术网

django:强制使用Unicode:需要字符串或缓冲区,找到int

django:强制使用Unicode:需要字符串或缓冲区,找到int,django,math,unicode,model,Django,Math,Unicode,Model,我在尝试对两个int值求和时遇到此错误: if dups.count() > 0: for item in dups: pi.quantity = pi.quantity+item.quantity pi和DUP都是同一型号的实例: class PurchaseItem(models.Model): picture = models.ForeignKey(Picture, null=False) paperType = models

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

if dups.count() > 0:
        for item in dups:
            pi.quantity = pi.quantity+item.quantity
pi和DUP都是同一型号的实例:

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将比2早11点。

您试过了吗

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))
但是,除非万不得已,否则不应该这样做,即使这样,也仍然不应该这样做,因为它掩盖了实际问题,而实际问题很可能会在今后造成更严重的问题


有可能发布完整的stacktrace吗?

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

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

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

您的代码: defunicode(自身): 返回self.id

应该是: defunicode(自身): 返回unicode(self.id)

只需更改最后一行即可

来自

返回self.id


return str(self.id)

to_python()抛出'unicode'对象没有属性'to_python'是由request.GET提交的这些值之一吗?如果是这样,那么get dict中的所有项都是字符串,您必须显式地将其转换为int。ftr request.POST执行相同的操作。