乘以django模板

vij*_*ker 8 python django django-templates

我正在循环推车项目,并希望将数量乘以单位价格,如下所示:

{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

有可能做那样的事吗?任何其他方式!谢谢

Rah*_*man 18

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

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

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

来源:链接

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

  • 似乎不适用于非理性值,即如何将值乘以1.5(似乎截断1.5到1.0) (4认同)

Bra*_*don 14

您需要使用自定义模板标记.模板过滤器只接受单个参数,而自定义模板标记可以接受所需数量的参数,进行乘法并将值返回到上下文.

您需要查看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
Run Code Online (Sandbox Code Playgroud)

你可以这样打电话:

{% load your_custom_template_tags %}

{% for cart_item in cart.cartitem_set.all %}
    {% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

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


小智 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
Run Code Online (Sandbox Code Playgroud)