*不支持的操作数类型:'NoneType'和'Decimal'

时间:2011-09-22 12:47:56

标签: python django tags null

我有一个管理增值税的django应用程序。例如,它可以计算来自欧盟的所有销售的增值税。

vat = purchases[0].vat.vat
eu_sales = Sale.objects.filter(country_type='2')
eu_amount = (eu_sales.aggregate(price = Sum('amount'))['price'])  * vat/100

但是,今天我将我的文件复制到另一台机器上。然后我收到了错误

unsupported operand type(s) for *: 'NoneType' and 'Decimal'

我意识到我收到此错误,因为尚未存储eu_amount值。在overwords中,没有eu_amount的值,因此它不能乘以十进制值。这是我在模板中的内容

{{eu_amount}}

有没有办法过滤这个模板标签?我想说的是,如果值为值为None,(或Null)则为0。

3 个答案:

答案 0 :(得分:3)

您可以尝试使用这样的默认值。

eu_amount = (eu_sales.aggregate(price = Sum('amount'))['price']) or 0  * vat/100

但最干净的方法可能是测试你的Sum是否返回任何内容,然后显示某种警告信息,因为这不应该发生。

答案 1 :(得分:0)

更改线路 vat = purchases[0].vat.vatvat = purchases[0].vat.vat or 0

答案 2 :(得分:0)

你是说这个?

{% if item %}
    something
{% else %}
    something different
{% endif %}

取自https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs

我几乎可以肯定,我最近在某个地方见过这个.vat.vat;)