Reputation: 133
i am trying to make a dict of dicts with data and pass it to template.
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)
i get an error:
Exception Value:
'QuerySet' object does not support item assignment
i am new to django and programming so take it easy.is this the right way to pass the data so i can show a list of files for each section for each lesson,in the template?
Upvotes: 0
Views: 546
Reputation: 599956
You don't need to convert to a dict of dicts to pass to the template. You can iterate through the queryset directly, and for each one you can get the related sections and files:
{% 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 %}
Note that this (just like your original approach) is very expensive in terms of database queries: you should investigate using prefetch_related
in the view to cut down on those.
Upvotes: 2