8

这是我与 Django 新生活的第二天,请原谅我的问题很简单。

我有一个现有的数据库表(只读访问),我已经使用 url、视图、模型和所有好东西成功地在网页上显示了它的内容。

我面临的挑战是表格不包含我需要显示的所有信息。该表包含测试结果,其中包含 sampletime、samplevalue、sampleresult 列。我需要根据我从这些列中计算出的数据来显示不同的数据。

我的最终目标是使用fltr将此信息显示为时间序列图。现在我很乐意将我需要的数据转储到网页上的表格中。(所以我可以可视化结果数据)

我想传递给模板的是,

  • jssampletime(sampletime datetime 对象转换为 javascript epoch ms)
  • 结果值(基于样本结果是好还是坏的样本值的滚动总和+-)

我可以使用 def 函数创建 jssampletime 和 resultvalue。我想我会将这些功能添加到views.py

我想我需要做的是遍历views.py 中的querySet 并将结果存储在我传递给模板的字典列表中。像这样的东西(代码未测试)。

视图.py

# views.py
# Sudo code to assit in asking the question
from django.shortcuts import render_to_response
from thing.reporter.models import Samples

def _datetime_to_js(sampletime):
    #.. date conversion epoch magic
    return jsd_result

def _rolling_sum(samplevalue,sampleresult):
    #.. summing magic
    return sum_result

def dumptable(request): # The def that is called by urls.py
    object_list = Samples.objects.all()

    list_for_template = []
    for row in object_list:
        jssampletime = _datetime_to_js(row.sampletime)
        resultvalue  = _rolling_sum(row.samplevalue,row.sampleresult) 
        list_for_template.append({'jssampletime':jssampletime,'resultvalue':resultvalue})   

    return render_to_response('tabledump.html', {'result_list': list_for_template})

tabledump.html

# tabledump.html template
{% block content %}
    <h2>Results dumped to page for testing</h2>
    <ul>
    <table>
    {% for result in result_list %}
        <tr>
        <td>{{ result.jssampletime }}</td>
        <td>{{ result.resultvalue }}</td>
        </tr>
    {% endfor %}
    </table>
    </ul>
{% endblock %}

我认为这可行,但我不确定它是否是 Django MVC 方式。

是不是我,

  • 通过对查询集结果进行交互来计算我在views.py中需要的结果?
  • 将我的结果作为字典列表传递给模板(查询集是否不止于此)?

我想我正在寻找一些方向和代码提示。我在正确的道路上吗?有没有更好的办法 ?

4

1 回答 1

17

如果您显示的信息在模型中,为什么不向模型添加属性/方法以显示您需要从中获取的任何信息?然后,您可以将实际的模型列表/查询集传递给您的模板,并将方法作为属性调用。

例如

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

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

如果您需要访问循环中的状态变量,请不要忘记您可以将任何属性附加到 python 对象。这可能非常有用。所以在你看来,你可以有类似的东西:

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

然后可以在模板中访问这两者:

{% 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 %}
于 2009-09-27T13:57:48.810 回答