2016-05-17 177 views
1

我查看了類似的問題,無法找到適合的解決方案或我錯過了什麼?我有兩個模型(SafetyCourse和SafetyCourseTaken)我有一個從以安全課程「採取安全課程」指向一個外鍵關係,如下圖所示:在Django模板中顯示外鍵值

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。我究竟做錯了什麼?

回答

4

看你的模式,我想應該是這樣的模板:

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

什麼?!?!就這麼簡單。那麼就像一個魅力。謝謝! – nastyn8