Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...