I need to get values from model fields, multiply and display the product in template.
For example, I have this code:
models.py
class Product(models.Model):
field1 = models.IntegerField()
field2 = models.IntegerField()
def multiply(self):
return self.field1 * self.field2
views.py
def home(request):
products = Product.objects.all()
#something goes here?
context = {
'products': products
}
return render(request, 'home.html', context)
template
{% for product in products %}
{{ product.field1 }}
{{ product.field2 }}
here goes the value of field1/field2 {{ }}
{% endfor %}
How it's better to achieve this?
You can add a method on the model:
def divided_fields(self):
return self.field1 / self.field2
And then im template:
{{ product.divided_fields }}
Another possibility would be to create a custom template tag or filter that handles division as there is no default tag or filter for such operations.
You can use django-mathfilters for this.
{% 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>