1👍
✅
You can add arbitrary data to the instances in the view without needing them to be model fields. This is fine:
for dividend in dividend_list:
dividend.change = ...calculation...
Just make sure you pass dividend_list
to your template context. Are you using class-based views or functional views? For class-based views, do this in get_context_data
and add this to the return value. For functional views, put the modified dividend
list (no longer a lazy evaluated queryset) into the dictionary argument:
return render(template_name, {'dividend_list': dividend_list})
Then iterate over it in the template.
{% for dividend in dividend_list %}
<tr>
<td>{{ dividend.date }}</td>
<td>${{ dividend.amount }} ({{ dividend.change }}%)</td>
<td>${{ dividend.price }}</td>
</tr>
{% endfor %}
You could also write a method on the Dividend model to do the calculation and then call it in the template loop, or even write a custom template tag to display the dividend.
Also, you really don’t want to use FloatField
to represent money. Use DecimalField
instead.
Source:stackexchange.com