2013-05-30 49 views
0

我正在嘗試製作一個字典的字典並將其傳遞給模板。將queryset轉換爲字典的字典django

models.py

class Lesson(models.Model): 
... 

class Files(models.Model): 
... 

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

views.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和編程,以便把它easy.is這傳遞數據的正確方式,以便我可以在模板中爲每個課程的每個部分顯示文件列表?

回答

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來減少這些。

+0

謝謝you.thought查詢必須在視圖中完成。 – belonious