Display foreign key value in django template

老子叫甜甜 提交于 2020-05-13 18:53:47

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37285061/display-foreign-key-value-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!