0

データを使用して辞書の辞書を作成し、それをテンプレートに渡そうとしています。

models.py

 class Lesson(models.Model):
 ...

 class Files(models.Model):
 ...

 class Section(models.Model):
   file = models.ManyToManyField(Files)
   lesson = models.ForeignKey(Lesson)

ビュー.py

def LessonView(request):
    the_data={}
    all_lessons= Lesson.objects.all()
    for lesson in all_lessons:
        the_data[lesson]=lesson.section_set.all()
        for section in the_data[lesson]:
            the_data[lesson][section]=section.file.all() <---error
    Context={
        'the_data':the_data,
        }
return render(request, 'TMS/lessons.html', Context)

エラーが発生します:

 Exception Value:   

 'QuerySet' object does not support item assignment

私はdjangoとプログラミングが初めてなので、簡単にしてください.これはデータを渡す正しい方法ですか?テンプレートで、各レッスンの各セクションのファイルのリストを表示できますか?

4

1 に答える 1

2

テンプレートに渡すために辞書の辞書に変換する必要はありません。クエリセットを直接反復処理して、それぞれに関連するセクションとファイルを取得できます。

{% for lesson in all_lessons %}
    {{ lesson.name }}
    {% for section in lesson.section_set.all %}
        {{ section.name }}
        {% for file in section.file.all %}
            {{ file.name }}
        {% endfor %}
    {% endfor %}
{% endfor %}

これは(元のアプローチと同じように)データベースクエリの点で非常に高価であることに注意してくださいprefetch_related。ビューで使用して調査し、それらを削減する必要があります。

于 2013-05-30T12:50:36.223 に答える