【问题标题】:Multiply in django template在 Django 模板中相乘
【发布时间】:2013-11-04 11:20:24
【问题描述】:

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

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

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

【问题讨论】:

标签: python django django-templates


【解决方案1】:

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

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

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

来源:link

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

【讨论】:

  • 比为简单操作编写自定义标签快得多
  • 似乎不适用于无理值,即如何将值乘以 1.5(似乎将 1.5 截断为 1.0)
  • @NicholasHamilton 正确,我没有注意到。结果将四舍五入为整数。
【解决方案2】:

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

你会想查看 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 %}

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

【讨论】:

    【解决方案3】:

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

    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
    

    【讨论】:

    • 模型逻辑更好,这是正确答案
    • 如何在 django 模板中直接访问这个?
    • 更好的解决方案,允许使用其他过滤器
    • @ManojSahu(对于现在的读者,我希望你早就知道了 :-):只需使用 {{ cart_item.total_cost }}
    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多