新手:Django:在传递给模板之前将计算结果添加到Queryset

7 django django-queryset

在我与Django的新生活的第二天,请原谅我的问题的简单性.

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

我遇到的挑战是该表不包含我需要显示的所有信息.该表包含测试结果,包括columns,sampletime,samplevalue,sampleresult.我需要根据我从这些列计算的内容显示不同的数据.

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

我想传递给模板的是,

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

我可以使用def函数创建jssampletime和resultvalue.我认为我会将这些函数添加到views.py中

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

views.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})
Run Code Online (Sandbox Code Playgroud)

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 %}
Run Code Online (Sandbox Code Playgroud)

我认为这会有效,但我不确定它是否是Django MVC方式.

我是对的,

  • 通过对查询集结果进行交互来计算views.py中我需要的结果?
  • 将我的结果传递给模板作为dict列表(是一个更多的查询集)?

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

Cor*_*ory 16

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

例如

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

    @property
    def calculated_field(self):
        return self._do_calculation(self.model_field)
Run Code Online (Sandbox Code Playgroud)

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

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

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

{% 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 %}
Run Code Online (Sandbox Code Playgroud)