在 Django 模板中显示外键值 [英] Display foreign key value in django template

查看:29
本文介绍了在 Django 模板中显示外键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了类似的问题,但找不到合适的解决方案,或者我遗漏了什么?我有两个模型(SafetyCourse 和 SafetyCourseTaken)我有一个外键关系,从安全课程"指向安全课程,如下所示:

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(模板)

course-taken.html(template)

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

针对类似问题,我尝试了多种解决方案,但未能找到正确的解决方案.我试过:course_taken.course_name_set.select_related、course_taken.course_name_set 和其他一些.我想要做的只是显示课程名称而不是课程 ID.我做错了什么?

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?

推荐答案

看你的schema,我觉得模板里应该是这样的:

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

这篇关于在 Django 模板中显示外键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆