简体   繁体   中英

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 teacherid that connects to it in TeacherCourseImplementation .
The problem is I don't see the part implement.teacherid when the template is opened on the browser. I don't know how should I do it if I want to get the teacher ID.

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

This is my models.py

class CourseImplementation(models.Model):
    courseid = models.ForeignKey(Course, on_delete=models.CASCADE, db_column='courseid', )
    roomid = models.ForeignKey('Room', models.DO_NOTHING, db_column='roomid', blank=True, null=True)
    note = models.CharField(max_length=10, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'course_implementation'

    def __str__(self):
        return self.pk + ' - ' + self.courseid

class TeacherCourseImplementation(models.Model):
    teacherid = models.ForeignKey(Teacher, on_delete=models.CASCADE, db_column='teacherid', primary_key=True)
    course_impleid = models.ForeignKey(CourseImplementation, on_delete=models.CASCADE, db_column='course_impleid')
    p1 = models.IntegerField(blank=True, null=True)
    p2 = models.IntegerField(blank=True, null=True)
    p3 = models.IntegerField(blank=True, null=True)
    p4 = models.IntegerField(blank=True, null=True)
    p5 = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'teacher_course_implementation'
        unique_together = (('teacherid', 'course_impleid'),)

    def __str__(self):
        return self.pk + ' - ' + self.teacherid

This is my template:

<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>

Can anyone help me on this. Thank you.

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 %}
    <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 %}

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 .

def get_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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM