Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

python - Display foreign key value in django template

I've looked through the similar questions and was unable to find a solution that fits or I'm missing something? I have two models(SafetyCourse and SafetyCourseTaken) I have a foreign key relationship that points from "safety courses taken" to safety course, shown below:

models.py

class SafetyCourse(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.name


class SafetyCoursesTaken(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    profile = models.ForeignKey(EmployeeProfile, on_delete=models.CASCADE)
    course = models.ForeignKey(SafetyCourse, on_delete=models.CASCADE, related_name='course_name')
    conducted_date = models.DateTimeField(null=True, blank=True)
    expiration_date = models.DateTimeField(null=True, blank=True)

    class Meta:
        verbose_name_plural = 'Safety Courses Taken'

views.py

class ManageSafetyCourseTakenView(LoginRequiredMixin, generic.ListView):
    login_url = reverse_lazy('users:login')
    model = SafetyCoursesTaken
    template_name = 'ppm/courses-taken.html'
    paginate_by = 10

    # override get_queryset to only show training related to employee profile
    def get_queryset(self):
        pk = self.kwargs['pk']
        return SafetyCoursesTaken.objects.filter(profile_id=pk)

course-taken.html(template)

{% for course_taken in object_list %}
    <tr>
        <td>{{ course_taken.course_id}}</td>
    </tr>
{% endfor %}

I've tried a number of solutions to similar questions but was unable to find a correct one. I've tried: course_taken.course_name_set.select_related, course_taken.course_name_set, and a few others. What I want to do is just display the name of the course instead of the course id. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looking at your schema, I think it should be this in the template:

{% for course_taken in object_list %}
    <tr>
        <td>{{ course_taken.course.name }}</td>
    </tr>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...