モデル内の関連フィールドの ID を取得してテンプレートに表示するために、約 1 日半を費やしました。IDが欲しいだけです。
問題のモデルは次のとおりです。
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})