You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django实现登录学生仅查看已选修课程的视图过滤方案咨询

Fixing the Query to Show Only Enrolled Courses

Hey there! Let's get your course list view working so logged-in students only see their enrolled courses. First, let's spot the issue with your current query—your syntax for filtering isn't quite right for Django's ORM. Here's how to fix it, with a couple of solid options:

Option 1: Direct Filter via Reverse Relationship

This is a clean, single-database query that leverages Django's ORM relationships to filter courses directly:

@login_required
def course_list(request):
    # Filter courses where the enrollment is linked to the current user
    courses = Course.objects.filter(enrollment__student=request.user)
    return render(request, "courses/course_list.html", {'courses': courses})

The enrollment__student part tells Django to follow the reverse relationship from Course to Enrollment to User, and only return courses where that user is the student on the enrollment.

Option 2: Fetch the User's Enrollment First (More Explicit)

Since you mentioned each student only has one Enrollment record, you can fetch that specific enrollment first, then get all linked courses. This is super readable:

@login_required
def course_list(request):
    # Get the single enrollment record for the current user (404 if none exists)
    enrollment = get_object_or_404(Enrollment, student=request.user)
    # Get all courses linked to this enrollment
    courses = enrollment.course.all()
    return render(request, "courses/course_list.html", {'courses': courses})

This works perfectly because your Enrollment model uses a ManyToManyField for courses, so calling .all() on enrollment.course gives you exactly the courses the student signed up for.

Why Your Original Query Failed

Your line courses = Course.objects.filter(id in Enrollment.objects.filter(student=request.user)) has two key issues:

  1. Django's ORM doesn't use the Python in keyword directly in filter arguments—you need to use the __in lookup instead.
  2. Enrollment.objects.filter(student=request.user) returns Enrollment objects, not course IDs, so comparing course IDs to these objects doesn't make sense. The relationship-based filters above fix this by letting Django handle the ID matching under the hood.

Either of these options will get you the result you want—pick the one that makes the most sense for your code style!

内容的提问来源于stack exchange,提问作者Sunil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:34:31