我查看了类似的问题并且无法找到适合的解决方案或者我错过了什么?我有两个模型(SafetyCourse和SafetyCourseTaken)我有一个外键关系,从“安全课程”到安全课程,如下所示:
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)
航向taken.html(模板)
{% 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。我做错了什么?
答案 0 :(得分:5)
查看您的架构,我认为它应该在模板中:
{% for course_taken in object_list %}
<tr>
<td>{{ course_taken.course.name }}</td>
</tr>
{% endfor %}