Skip to content Skip to sidebar Skip to footer

How To Properly Use Get_context_data With Listview To Fetch Related Instances In Django

I am trying to use ListView and ContextMixin to create a view but I'm not sure if this is a right way to do it. The goal is to get all the fields in CourseImplementation and the te

Solution 1:

You can access the related TeacherCourseImplementation items for a TeacherCourseImplementation item implement with implement.teachercourseimplementation_set.all() (don't use parentheses in the template):

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

See the docs on following relationships backwards for more info.

This will generate an extra query for every item in the queryset. You can avoid this by using prefetch_related.

defget_queryset(self):
    return CourseImplementation.objects.all().prefetch_related('teachercourseimplementation_set')

Since you are accessing all the TeacherCourseImplementation instances via the CourseImplementation instances, you don't need to override get_context_data.

Post a Comment for "How To Properly Use Get_context_data With Listview To Fetch Related Instances In Django"