2010-12-30 1 views

答えて

1
{% for task in tasks %} 
    {% for comment in task.comment_set.all|slice:"5" %} 
    {{ comment }} 
    {% endfor %} 
{% endfor %} 
+0

ありがとう、それも同様に動作します。 どちらが良い方法ですか? –

+0

まあそこには、データのそのようなわずかな操作を可能にする多くのdjangoテンプレートタグ/フィルタがありますので、私はそのmvcコンセプトのそのような大きな違反を見ていないでしょう、また、djangoは、 docs.djangoproject.com/ja/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-control-the-view-and-the-view-the -template-how-come-you-don-t-use-the-standard-names –

1

あなたがいない:

{% for task in tasks %} 
    {% for comment in task.comment_set.all %} 
    {{ comment }} 
    {% endfor %} 
... 

などの5つのコメントに、これを制限するための最良の方法は何ですか。あなたはテンプレートで "本物の仕事"をするべきではない、これはMVC patternを破る。

ビューで実際の作業を行い、(コンテキスト辞書を使用して)テンプレートにデータを渡します。

def handle_comments(request): 
    tasks = Task.objects.all() 
    comments = {} 
    for task in tasks: 
     comments[task] = task.comment_set.all()[:5] 
    return render_to_response('commenting.html', {'comments': comments}) 

次に、あなたのテンプレートにコメントを反復処理することができます

{% for task, task_comments in comments.items %}{{ task }}{% endfor %} 
+0

作品&感謝をMVCパターンに私にヒントを与えるため。 –

関連する問題