如何正确使用get_context_data和ListView来获取Djang中的相关实例

2024-09-30 14:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用ListView和ContextMixin来创建一个视图,但是我不确定这是否是一个正确的方法。目标是获取CourseImplementation中的所有字段以及与之相关的teacherid 问题是我看不到那部分工具.teacherid在浏览器上打开模板时。我不知道如果我想得到老师该怎么做。在

class ImplementView(generic.ListView):
    template_name = 'schedule/implement.html'
    context_object_name = 'all_implements'

    def get_queryset(self):
        return CourseImplementation.objects.all()

    def get_context_data(self, **kwargs):
        context = super(ImplementView, self).get_context_data(**kwargs)
        context['teacherid'] = TeacherCourseImplementation.objects.all()
        return context

这是我的模型.py在

^{pr2}$

这是我的模板:

<ul>
    {% for implement in all_implements %}
        <div class="col-sm-5 col-lg-5">
            <div class="thumbnail">
                <p>{{ implement.teacherid }} - {{ implement.courseid }}</p>
            </div>
        </div>
    {% endfor %}
</ul>

有人能帮我吗。谢谢您。在


Tags: nameselfdiv模板getdefcontextall
1条回答
网友
1楼 · 发布于 2024-09-30 14:28:26

可以使用implement.teachercourseimplementation_set.all()访问TeacherCourseImplementation项的相关TeacherCourseImplementation项{}(不要在模板中使用括号):

{% for implement in all_implements %}
    <div class="col-sm-5 col-lg-5">
        <div class="thumbnail">
            <p>{{ implement.courseid }}</p>
            {% for teacher_course_implementation in implement. teachercourseimplementation_set.all %}
              {{ teacher_course_implementation.teacherid }}
              ...
            {% endfor %}
        </div>
    </div>
{% endfor %}

有关详细信息,请参阅following relationships backwards上的文档。在

这将为queryset中的每个项生成一个额外的查询。您可以使用^{}来避免这种情况。在

^{pr2}$

因为您是通过CourseImplementation实例访问所有TeacherCourseImplementation实例,所以不需要重写{}。在

相关问题 更多 >