Newbie: Django : Adding calculated results to Queryset before passing to template

痴心易碎 提交于 2019-12-04 04:16:04

If the information you are displaying is in a model why not just add properties/methods to the model to display whatever information you need to get out of it? Then you can pass the actual model list / query set to your template and call the methods as properties.

e.g.

class MyModel(models.Model):
    model_field = models.CharField(max_length=255)

    @property
    def calculated_field(self):
        return self._do_calculation(self.model_field)

If you need access to state variables in your loop, don't forget that you can attach any property to a python object. This can be extremely useful. So in your view you could have something like:

for row in object_list:
    # update some variable we want to use in the template
    row.newly_added_field = run_calculation(row, somevariable)

Both of these could then be accessed within the template:

{% for result in result_list %}
    <tr>
    <!-- some stuff that displays the model directly -->
    <td>{{ result.calculated_field}}</td>
    <td>{{ result.newly_added_field}}</td>
    </tr>
{% endfor %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!