Новичок: Django: Добавление расчетных результатов к Queryset прежде, чем передать шаблону

Не уверенный в лучших практиках, но по моему опыту несколько панелей работают хорошо и уменьшают объем данных, отправляемый когда-то - приводящий к увеличению в ответ время в целом. Несколько панелей также уменьшают сложность каждого вызова сервера.

7
задан 27 September 2009 в 11:47
поделиться

1 ответ

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 %}
16
ответ дан 6 December 2019 в 12:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: