我一直在嘗試約一天半,以獲取模型中相關字段的ID以顯示在我的模板中。沒什麼奇特的,我只想要這個ID。無法獲取在Django模板中顯示的密鑰
這裏是有問題的模式:
class CompositeLesson(models.Model):
lesson = models.ForeignKey(Lesson)
student = models.ForeignKey(Student)
actualDate = models.DateTimeField()
假設我有一個列表,lessonsList
的CompositeLesson
和我能夠成功地遍歷列表。其他字段(即actualDate)正確顯示。
的片段模板代碼:
{% for lesson in lessonsList %}
<tr{% if forloop.counter|divisibleby:"2" %} class="shaded_row"{% endif %}>
<td>{{ lesson.actualDate }}</td>
<td class="table_button">
{% if not lesson.isCancelled %}
<div class="table_button_div" id="cancel_{{ lesson__lesson__id }}"><a href="#">Cancel Lesson</a></div>
{% else %}
<div class="cancelled_lesson"></div>
{% endif %}
的問題是我不能讓課程對象是在列表中的ID。我試過了:
lesson.lesson
lesson.lesson.id
lesson.lesson__id
lesson__lesson__id
lesson.lesson.get_id
...並且它們都沒有工作。
在此先感謝!
編輯:這是我的觀點,即構建教訓,每個請求:
def all_student_lessons(request, id):
# This should list all lessons up to today plus the next four, and call out any cancelled or unpaid lessons
# User should have the option to mark lessons as paid or cancel them
s = Student.objects.get(pk = id)
if s.teacher != request.user:
return HttpResponseForbidden()
less = Lesson.objects.filter(student = id)
lessonsList = []
for le in less:
if le.frequency == 0:
# lesson occurs only once
x = CompositeLesson()
x.lessonID = le.id
x.studentID = id
x.actualDate = datetime.combine(le.startDate, le.lessonTime)
x.isCancelled = False
try:
c = CancelledLesson.objects.get(lesson = le.id, cancelledLessonDate = le.startDate)
x.canLesson = c.id
x.isCancelled = True
except:
x.canLesson = None
try:
p = PaidLesson.objects.get(lesson = le.id, actualDate = le.startDate)
x.payLesson = p.id
except:
x.payLesson = None
lessonsList.append(x)
else:
sd = next_date(le.startDate, le.frequency, le.startDate)
while sd <= date.today():
x = CompositeLesson()
x.lessonID = le.id
x.studentID = id
x.actualDate = datetime.combine(sd, le.lessonTime)
x.isCancelled = False
try:
c = CancelledLesson.objects.get(lesson = le.id, cancelledLessonDate = le.startDate)
x.canLesson = c.id
x.isCancelled = True
except:
x.canLesson = None
try:
p = PaidLesson.objects.get(lesson = le.id, actualDate = le.startDate)
x.payLesson = p.id
except:
x.payLesson = None
lessonsList.append(x)
sd += timedelta(le.frequency)
lessonsList.sort(key = lambda x: x.actualDate)
return render_to_response('manage_lessons.html', {'lessonsList': lessonsList,
's': s})
你有沒有試過'lesson.lesson.pk'? –
將'lesson.lesson.pk'添加到我嘗試過的那些不起作用的列表中,遺憾的是... –
您如何在視圖中創建lessonsList?嘗試添加一個'select_related('lesson')'到你的過濾器。 –