Home  >  Q&A  >  body text

python - django 模板里如何多个值相加?

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

求解,或者有没有其他的实现方法?

PHP中文网PHP中文网2741 days ago484

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:32:19

    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:

    
    |-- views.py
    |-- models.py
    |templatetags
        |-- __init__.py
        |-- add_value.py
    

    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:

    # coding:utf-8
    __author__ = 'Dell'
    from django import template
    
    register = template.Library()
    
    
    @register.filter(name='add_value')
    def add_value(values):
        count = 0
        # 这里的values就是你使用该标签时传入的参数,在这个例子里面values就是render的时候传给模板的order_list的值
        # 所以这里可以根据你实际传入的值做处理
        for v in values:
            if v['key']:
                count += int(v['key'])
        return count
    

    Step 3: In views.py:

    
    # 这里假设你order_list的值是[{'key': 1}, {'key': 2}, {'key': 3}]
    render(request, 'orders/order_list.html', {'order_list': [{'key': 1}, {'key': 2}, {'key': 3}]})
    

    Step 4: Add {% load add_value %},然后使用<p>{{ order_list|add_value }}</p>

    to your order_list.html template

    In the end, you should be able to achieve your needs. I hope it can help you.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:32:19

    Can’t you handle it directly in the view and then reference it in the template?

    reply
    0
  • Cancelreply