在Django模板中乘法

问题描述 投票:8回答:4

我正在遍历购物车项目,并希望将数量与单价相乘:

{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}

是否可以做类似的事情?任何其他方式做到这一点!谢谢

python django django-templates
4个回答
14
投票

您需要使用自定义模板标签。模板过滤器仅接受一个参数,而自定义模板标签可以接受所需数量的参数,进行乘法运算并将值返回到上下文。

您将要查看Django template tag documentation,但简单的例子是:

from django import template
register = template.Library()

@register.simple_tag()
def multiply(qty, unit_price, *args, **kwargs):
    # you would need to do any localization of the result here
    return qty * unit_price

您可以这样打电话:

{% load your_custom_template_tags %}

{% for cart_item in cart.cartitem_set.all %}
    {% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}

您确定不想将此结果设为购物车商品的属性吗?结帐时,您似乎需要将此信息作为购物车的一部分。


18
投票

您可以使用widthratio内置滤波器进行乘法和除法。

要计算A * B: {% widthratio A 1 B %}

要计算A / B: {% widthratio A B 1 %}

来源:link

注意:对于无理数,结果将舍入为整数。


8
投票

或者您可以在模型上设置属性:

class CartItem(models.Model):
    cart = models.ForeignKey(Cart)
    item = models.ForeignKey(Supplier)
    quantity = models.IntegerField(default=0)

    @property
    def total_cost(self):
        return self.quantity * self.item.retail_price

    def __unicode__(self):
        return self.item.product_name

0
投票

您可以在带有过滤器的模板中进行此操作。

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

来自文档:

这是示例过滤器定义:

def cut(value, arg):
    """Removes all values of arg from the given string"""
    return value.replace(arg, '')

这是该过滤器的使用示例:

{{ somevariable|cut:"0" }}
© www.soinside.com 2019 - 2024. All rights reserved.