【问题标题】:transform queryset to dict of dicts django将queryset转换为dicts django的dict
【发布时间】:2013-05-25 22:29:45
【问题描述】:

我正在尝试用数据制作一个字典并将其传递给模板。

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 和编程新手,所以放轻松。这是传递数据的正确方法,以便我可以在模板中为每节课的每个部分显示文件列表吗?

【问题讨论】:

    标签: django python-3.x django-views django-queryset


    【解决方案1】:

    您无需转换为 dict 的 dict 即可传递给模板。您可以直接遍历查询集,并为每个查询集获取相关部分和文件:

    {% 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 进行调查以减少这些查询。

    【讨论】:

      猜你喜欢
      • 2014-12-17
      • 2017-05-17
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2013-09-07
      相关资源
      最近更新 更多