Python django模板中的乘法
我正在循环浏览购物车项目,并希望将数量乘以单价,如下所示:Python django模板中的乘法,python,django,django-templates,Python,Django,Django Templates,我正在循环浏览购物车项目,并希望将数量乘以单价,如下所示: {% for cart_item in cart.cartitem_set.all %} {{cart_item.quantity}}*{{cart_item.unit_price}} {% endfor %} {% load your_custom_template_tags %} {% for cart_item in cart.cartitem_set.all %} {% multiply cart_item.quan
{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}
{% load your_custom_template_tags %}
{% for cart_item in cart.cartitem_set.all %}
{% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}
有可能做那样的事吗?还有别的办法吗!!谢谢您可以在带有过滤器的模板中完成 从文件: 下面是一个示例过滤器定义:
def cut(value, arg):
"""Removes all values of arg from the given string"""
return value.replace(arg, '')
下面是如何使用该过滤器的示例:
{{ somevariable|cut:"0" }}
您需要使用自定义模板标记。模板过滤器只接受一个参数,而自定义模板标记可以根据需要接受任意多个参数,执行乘法运算并将值返回到上下文 您可能想查看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
你可以这样称呼它:
{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}
{% load your_custom_template_tags %}
{% for cart_item in cart.cartitem_set.all %}
{% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}
您确定不想将此结果设为购物车项目的属性吗?当您结账时,似乎需要将此信息作为购物车的一部分。或者您可以在模型上设置属性:
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
您可以使用
widthratio
内置的乘法和除法过滤器
计算A*B:{%widthratio A 1 B%}
计算A/B:{%widthratio A B 1%}
资料来源:
注意:对于无理数,结果将四舍五入为整数。这是一个巧妙使用过滤器的方法,可能重复。我不认为使用
cart\u item.quantity
作为value
和cart\u item.unit\u price
作为arg的逻辑在模型中更好,这是正确的答案如何在django模板中直接访问它?更好的解决方案,允许使用其他方法filters@ManojSahu (对于现在的读者,我希望你们很久以前就发现:-):只需使用{{cart\u item.total\u cost}}
比为一个简单的操作编写一个自定义标记要快得多。对于非理性的值,似乎不起作用,例如,如何将值乘以1.5(似乎将1.5截断为1.0)@NicholasHamilton正确,我没有注意到。结果将四舍五入为整数。