8

Django との新しい生活の 2 日目です。質問が単純で申し訳ありません。

URL、ビュー、モデル、およびそのすべての優れたものを使用して、Webページにコンテンツを正常に表示した既存のDBテーブル(読み取り専用アクセス)があります。

私が抱えている課題は、表示する必要があるすべての情報がテーブルに含まれていないことです。このテーブルには、列 sampletime、samplevalue、sampleresult を含むテスト結果が含まれています。これらの列から計算した内容に基づいて、さまざまなデータを表示する必要があります。

私の最終目標は、flotrを使用して、この情報を時系列グラフとして表示することです。今のところ、必要なデータを Web ページのテーブルにダンプするだけで十分です (結果のデータを視覚化できます)。

Id がテンプレートに渡したいのは、

  • jssampletime (javascript epoch ms に変換された sampletime 日時オブジェクト)
  • resultvalue (sampleresult の良し悪しに基づく samplevalue のローリング サム +-)

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 で必要な結果を計算しますか?
  • 結果をdictのリストとしてテンプレートに渡します(クエリセットはそれ以上ですか)?

私はいくつかの方向性とコードのヒントを探していると思います。私は正しい道を進んでいますか?より良い方法はありますか?

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 に答える