如何在Django单个视图中通过lesson_id获取关联Student模型数据?
问题解决:通过Lesson关联获取对应的Student实例
问题说明
需要在视图中传递Lesson模型的lesson.price、lesson.invoice_id,以及Student模型的student.student_id到模板展示,但Lesson的student字段是指向User模型的外键,当前视图代码无法正确获取对应Lesson的Student实例。
问题分析
你的Student类继承自User类,属于Django的多表继承,Django会自动为Student创建一对一关联的user_ptr字段,关联到父类User。当Lesson关联的User是Student用户时,可通过该一对一关联直接获取Student实例,无需额外绕路查询。
当前视图中student = Lesson.student.get(student_id=lesson.student.student_id)的写法错误:Lesson.student是外键字段,不能直接调用get方法,且逻辑冗余。
解决方案
修正后的视图代码
直接利用多表继承的反向关联属性获取Student实例,或通过显式查询确保稳定性:
def invoice(request, lesson_id): lesson = Lesson.objects.get(lesson_id=lesson_id) # 方式1:利用多表继承自动生成的反向关联属性 student = lesson.student.student # 方式2:显式查询(适用于需要严格校验用户类型的场景) # student = Student.objects.get(user_ptr=lesson.student) return render(request, 'invoice.html', {'lesson': lesson, 'student': student})
模板代码修正
原模板中{{lesson.student_id}}为错误写法,需改为调用student对象的student_id属性:
{% extends 'student/student_home_base.html' %} {% block student_content %} <h1>Your Invoice</h1> <p>Your invoice reference number is {{student.student_id}}-{{lesson.invoice_id}}</p> <p>Your Total Payable is {{lesson.price}}</p> <p>Once you're done paying, please click this button below.</p> <input type="submit" value="submit"> {% endblock %}
可选:添加异常处理
若需避免关联用户非Student类型导致的错误,可添加异常捕获:
from django.http import Http404 def invoice(request, lesson_id): lesson = Lesson.objects.get(lesson_id=lesson_id) try: student = lesson.student.student except Student.DoesNotExist: raise Http404("对应的Student不存在") return render(request, 'invoice.html', {'lesson': lesson, 'student': student})
内容的提问来源于stack exchange,提问作者Jae
相关产品推荐
相关产品推荐

