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

Django中如何配置ListView仅返回学生已购买的课程?

解决学生已购课程列表展示问题

你的代码中get_queryset方法的过滤逻辑存在语法错误,导致无法正确获取学生已购买的课程。以下是修正方案:

问题原因

Course.objects.filter(pk=self.request.user.purchased.all())不符合Django ORM的查询规则:pk字段需要匹配单个值,而self.request.user.purchased.all()返回的是课程对象的QuerySet,不能直接作为pk的匹配值。

修正后的代码

方案一:直接利用多对多关联获取(推荐)

直接通过用户的purchased多对多字段获取已购课程,代码更简洁高效:

class StudentPurchasedcourse(ListView):
    model = Course
    template_name = 'tutspack/purchasedcourse.html'
    context_object_name = 'course'
    
    def get_queryset(self):
        # 直接从当前用户的已购课程集合中获取并排序
        return self.request.user.purchased.all().order_by('title')

方案二:使用__in查询过滤

如果需要通过Course模型查询,可先提取已购课程的ID列表,再用pk__in匹配:

class StudentPurchasedcourse(ListView):
    model = Course
    template_name = 'tutspack/purchasedcourse.html'
    context_object_name = 'course'
    
    def get_queryset(self):
        # 获取已购课程的ID列表
        purchased_ids = self.request.user.purchased.values_list('pk', flat=True)
        # 通过ID过滤课程并排序
        return Course.objects.filter(pk__in=purchased_ids).order_by('title')

额外优化:增加登录验证

为了确保只有登录的学生能访问该页面,建议继承LoginRequiredMixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class StudentPurchasedcourse(LoginRequiredMixin, ListView):
    model = Course
    template_name = 'tutspack/purchasedcourse.html'
    context_object_name = 'course'
    
    def get_queryset(self):
        return self.request.user.purchased.all().order_by('title')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:45:45