【问题标题】:How to display Foreign Key related models fields values in HTML with Django?如何使用 Django 在 HTML 中显示与外键相关的模型字段值?
【发布时间】:2020-08-01 22:30:04
【问题描述】:

我将 Views.py 中的列表以字典值的形式传递给 HTML。我在田野里循环。有一列是另一个模型的外键。只有该模型相关信息未在 HTML 中显示。如何解决这个问题?以下是代码。外键列“课程”未显示,但其他。 Screenshot attached here

Views.py

def Student_Main(request):
    objs= Students.objects.values().all()
    template_name = 'genius/students.html'
    context = {'head_title': 'Little Genius Students', 'students':objs}
    return render(request, template_name, context)

HTML

<table class="table table-hover">
                <thead class="thead-dark">
                    <tr>
                    <th scope="col">#</th>
                    <th scope="col">Name</th>
                    <th scope="col">DOB</th>
                    <th scope="col">Age</th>
                    <th scope="col">Gender</th>
                    <th scope="col">Grade</th>
                    <th scope="col">School</th>
                    <th scope="col">Course</th>
                    <th scope="col">Address</th>

                    </tr>
                </thead>
                <tbody>
                    {% for i in students %}
                    <tr>
                    <th scope="row">{{i.id}}</th>
                    <td><a href=''>{{i.name}}</a></td>
                    <td>{{i.dob}}</td>
                    <td>{{i.age}}</td>
                    <td>{{i.gender}}</td>
                    <td>{{i.grade}}</td>
                    <td>{{i.attending_school}}</td>
                    <td>{{i.course.class_name}}</td>
                    <td>{{i.address}}</td>
                    </tr>
                    {% endfor %}
                </tbody>
</table>

【问题讨论】:

    标签: python html django python-3.x


    【解决方案1】:

    不要使用.values() [Django-doc],它应该很少使用,例如,如果你想在一组值上创建一个GROUP BY。省略.values() 将返回Model 对象,这些对象利用延迟加载来跟随ForeignKeys:

    def Student_Main(request):
        # no .values()
        objs = Students.objects.all()
        template_name = 'genius/students.html'
        context = {'head_title': 'Little Genius Students', 'students':objs}
        return render(request, template_name, context)

    您可以利用.select_related(..) [Django-doc]来防止N+1问题,并在查询中选择相关课程:

    def Student_Main(request):
        objs = Students.objects.select_related('course')
        template_name = 'genius/students.html'
        context = {'head_title': 'Little Genius Students', 'students':objs}
        return render(request, template_name, context)

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      相关资源
      最近更新 更多