models.py
class Order(models.Model):
price_a = models.PositiveIntegerField(blank=True, null=True)
price_b = models.PositiveIntegerField(blank=True, null=True)
price_c = models.PositiveIntegerField(blank=True, null=True)
views.py
def order_list():
order_list = Order.objects.all()
return render(request, 'orders/order_list.html', {'order_list': order_list})
模板:
{% for order in order_list %}
price_* 可能是 None
这里想输出 price_a + price_b + price_b 的总和
下面这个写法没有用:
{{ price_a|add:price_b|add:price_c }}
{% endfor %}
求解,或者有没有其他的实现方法?
Based on the needs you mentioned, there are two solutions:
1. Calculate it in views.py and then transfer it to the template;
2. Customize template filters to implement it. The specific implementation method is as follows:
Step one: Create a new templatetags folder in the app directory of your project (this folder is at the same level as your views.py and models.py), and create new __init__.py and add_value.py files in this folder , the directory structure is as follows:
Step 2: Edit the __init__.py and add_value.py files. The __init__.py file can be empty. The content of the add_value.py file is as follows:
Step 3: In views.py:
Step 4: Add
to your order_list.html template{% load add_value %}
,然后使用<p>{{ order_list|add_value }}</p>
In the end, you should be able to achieve your needs. I hope it can help you.
Can’t you handle it directly in the view and then reference it in the template?