Python 如何在模板中显示计算数据
我需要从模型字段中获取值,乘以并在模板中显示产品 例如,我有以下代码: 型号.pyPython 如何在模板中显示计算数据,python,django,Python,Django,我需要从模型字段中获取值,乘以并在模板中显示产品 例如,我有以下代码: 型号.py class Product(models.Model): field1 = models.IntegerField() field2 = models.IntegerField() def multiply(self): return self.field1 * self.field2 def home(request): products = Product.o
class Product(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField()
def multiply(self):
return self.field1 * self.field2
def home(request):
products = Product.objects.all()
#something goes here?
context = {
'products': products
}
return render(request, 'home.html', context)
视图.py
class Product(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField()
def multiply(self):
return self.field1 * self.field2
def home(request):
products = Product.objects.all()
#something goes here?
context = {
'products': products
}
return render(request, 'home.html', context)
模板
{% for product in products %}
{{ product.field1 }}
{{ product.field2 }}
here goes the value of field1/field2 {{ }}
{% endfor %}
如何更好地实现这一点?您可以在模型上添加一个方法:
def divided_fields(self):
return self.field1 / self.field2
然后是im模板:
{{ product.divided_fields }}
另一种可能是创建处理除法的自定义模板标记或过滤器,因为此类操作没有默认标记或过滤器。您可以在模型上添加方法:
def divided_fields(self):
return self.field1 / self.field2
然后是im模板:
{{ product.divided_fields }}
另一种可能是创建处理除法的自定义模板标记或过滤器,因为此类操作没有默认标记或过滤器。您可以使用它
{% load mathfilters %}
...
<h1>Basic math filters</h1>
<ul>
<li>8 + 3 = {{ 8|add:3 }}</li>
<li>13 - 17 = {{ 13|sub:17 }}</li>
{% with answer=42 %}
<li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
{% endwith %}
{% with numerator=12 denominator=3 %}
<li>12 / 3 = {{ numerator|div:denominator }}</li>
{% endwith %}
<li>|-13| = {{ -13|abs }}</li>
</ul>
{%load mathfilters%}
...
基本数学过滤器
- 8+3={8|add:3}
- 13-17={13|sub:17}
{答案为42%的百分比}
- 42*0.5={{答案| mul:0.5}
{%endwith%}
{分子=12,分母=3%}
- 12/3={{分子|分母}
{%endwith%}
- |-13 |={{-13 | abs}
您可以使用它
{% load mathfilters %}
...
<h1>Basic math filters</h1>
<ul>
<li>8 + 3 = {{ 8|add:3 }}</li>
<li>13 - 17 = {{ 13|sub:17 }}</li>
{% with answer=42 %}
<li>42 * 0.5 = {{ answer|mul:0.5 }}</li>
{% endwith %}
{% with numerator=12 denominator=3 %}
<li>12 / 3 = {{ numerator|div:denominator }}</li>
{% endwith %}
<li>|-13| = {{ -13|abs }}</li>
</ul>
{%load mathfilters%}
...
基本数学过滤器
- 8+3={8|add:3}
- 13-17={13|sub:17}
{答案为42%的百分比}
- 42*0.5={{答案| mul:0.5}
{%endwith%}
{分子=12,分母=3%}
- 12/3={{分子|分母}
{%endwith%}
- |-13 |={{-13 | abs}
我不太明白你的问题。模型上有一个multiply
方法,为什么不能有一个divide
方法呢?对不起,我弄错了。我只是以除法为例,我不太明白你的问题。模型上有一个multiply
方法,为什么不能有一个divide
方法呢?对不起,我弄错了。我只是想以师为例,这正是我想要的。非常感谢你!这正是我想要的。非常感谢你!