10

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

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

有可能做这样的事情吗?任何其他方式来做到这一点!谢谢

4

4 回答 4

34

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

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

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

来源:链接

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

于 2015-10-22T12:19:13.983 回答
20

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

您需要查看 Django模板标签文档,但一个简单的示例是:

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 %}

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

于 2013-10-25T11:31:32.350 回答
11

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

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
于 2015-03-11T16:06:39.993 回答
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" }}
于 2013-10-25T11:11:40.447 回答