django不能乘以'str'类型的非int

时间:2015-06-15 12:28:24

标签: python django

我是python& amp;的初学者django编码。

我有这个型号:

class QuoteRow(models.Model):
    (...)
    quantity = models.IntegerField(blank=True, null=True)
    unit_price = models.DecimalField(max_digits=12, decimal_places=6, blank=True, null=True)

这些行在另一个模型'引用'中:

 def _total_amount(self):
        return QuoteRow.objects.filter(quote=self.pk).aggregate(Sum('unit_price' * 'quantity'))
 total_amount = property(_total_amount)

在shell中:

q=Quote.objects.get(pk=2) // valid instance
q.total_amount
>>> TyperError: can't multiply sequenceby non-int of type 'str'

我只能将“单位价格”列或仅“数量”列相加而没有问题。

谢谢。

2 个答案:

答案 0 :(得分:1)

尝试使用extra()

QuoteRow.objects.filter(quote=self.pk).extra(select = {'total': 'SUM(unit_price * quantity)'},)

答案 1 :(得分:0)

I would use this:

def _total_amount(self):
    req = QuoteRow.objects.filter(quote=self.pk)
    return sum([i.unit_price * i.quantity for i in req])

It takes one more line but it's clearer to me.