使用TemplateTag处理计算返回None

时间:2017-12-04 14:37:15

标签: python django django-models

我有一个模型 Coper 和一个要求用户选择是否需要动态获取报价的字段。因此,如果用户选择“动态”,则用户将获得产品报价和其他费用。

所以我写了一个模板标签,它将获取产品的ID,过滤卖家的货币并在另一个模型中查找费率并完成报价。

@register.filter(name='get_total_quote')
def get_total_quote(value):
    tap = Coper.objects.get(pk=value)
    get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency)
    ratex = get_cnd.money_rate
    if tap.margin_type == 'plus':
        percent = tap.margin_figure / 100
        addup =  ratex * percent
        total_amt = ratex + addup
        return total_amt
    if tap.margin_type == 'minus':
        percent = tap.margin_figure / 100
        addup =  ratex * percent
        total_namt = ratex - addup
        return total_namt

模板

{% load quote_filter %}
    {% for m in all_quotes %}
        {% if m.pricing == 'dynamic' %}
            {{m.id|get_total_quote }}
        {% else %}
           <p> Fixed price is $3500 </p>
        {% endif %}
    {% empty %}
       <p> No product yet. </p>
     {% endfor %}

当我加载网站时,我得到 NONE 作为动态报价的价格而不是实际数字。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

如果if语句都不为True,则您的代码会返回None

if tap.margin_type == 'plus':
    ...
    return total_amt
if tap.margin_type == 'minus':
    ...
    return total_amt
# if code gets to this point, you are implicitly returning None

正如Daniel在评论中建议的那样,您可以将Coper对象直接传递给标记:

{{m|get_total_quote }}

然后更改过滤器以接受tap并移除tap = Coper.objects.get(pk=value)

@register.filter(name='get_total_quote')
def get_total_quote(tap):
    get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency)
    ...