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

Django校园管理应用:学生选课后教师无法获取关联学生信息

校园管理应用:学生选课信息无法在教师课程表中显示的解决方案

我正在开发一款校园管理应用,已实现教师创建课程表、学生查看并选课功能,但学生选课后,教师无法查看对应学生信息。当前课程表的时间和时长可正常显示,但学生用户名、英文名、ID完全无法加载,排查发现是Student与Schedule模型关联及后续逻辑存在问题,以下是具体修复方案:


一、模型层关联修正

1. 调整选课关联逻辑

原Schedule模型中用ForeignKey关联单个学生,若支持单课程多学生报名(即使capacity=1),建议改为多对多关联;若为一对一授课场景,保持ForeignKey但需确保关联逻辑正确:

# 多学生选课场景(推荐)
class Schedule(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date = models.DateField(null=True, blank=True)
    time = models.TimeField(null=True, blank=True)
    duration = models.TextField(null=True, blank=True)
    capacity = models.PositiveSmallIntegerField(default=1)
    # 替换原student字段为多对多关联
    students = models.ManyToManyField(Student, blank=True)

    def __str__(self):
        student_names = ", ".join([s.englishName for s in self.students.all()]) if self.students.exists() else "No Student"
        return f"{self.date} {self.time} - {student_names}"

# 一对一授课场景
class Schedule(models.Model):
    # 其他字段不变
    student = models.ForeignKey(Student, null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return f"{self.date} {self.time} - {self.student.englishName if self.student else 'No Student'}"

2. 修复重名视图函数

原代码中两个index视图重名会导致路由冲突,需改名区分:

def student_index(request):
    data = Student.objects.all()
    context = {'students': data}
    return render(request, 'student-information.html', context)

def schedule_index(request):
    data = Schedule.objects.filter(user=request.user)
    context = {'schedules': data}
    return render(request, 'set-schedule.html', context)

二、视图层逻辑优化

原视图中单独收集students列表属于冗余操作,且未过滤当前教师的课程,优化后:

@login_required
@allowed_users(allowed_roles=['teacher'])
def dailySchedule(request):
    today = datetime.now().date()
    # 仅显示当前教师的今日课程
    schedules = Schedule.objects.filter(user=request.user, date=today)
    # 提前加载关联学生数据,减少数据库查询次数
    if hasattr(Schedule, 'student'):
        schedules = schedules.select_related('student')
    else:
        schedules = schedules.prefetch_related('students')
    
    context = {'today': today, 'schedules': schedules}
    return render(request, 'eslbeeph/daily-schedule.html', context)

三、模板层渲染修复

原模板嵌套students循环逻辑错误,直接通过课程关联的学生对象渲染即可:

{% extends 'main.html' %}
{% block content %}

<div class="container-fluid">
    <div class="daily-schedule-title">
        <h3 class="daily-schedule-header">Schedule</h3>
    </div>
    <div class="daily-schedule-table">
        <table class="daily-schedule">
            <tr>
                <th>Date</th>
                <th colspan="6">{{ today|date:"F d, Y" }}</th>
            </tr>
            <tr>
                <th>Start Time</th>
                <th>Account</th>
                <th>Duration</th>
                <th>Student ID</th>
                <th>Student Name</th>
                <th>Class Status</th>
                <th>Student Profile</th>
            </tr>
            {% for schedule in schedules %}
            <tr>
                <td>{{ schedule.time|date:"H:i" }}</td>
                {% if schedule.student %}
                    <!-- 一对一场景渲染 -->
                    <td>{{ schedule.student.user.username }}</td>
                    <td>{{ schedule.duration }}</td>
                    <td>{{ schedule.student.studentId }}</td>
                    <td>{{ schedule.student.englishName }}</td>
                {% elif schedule.students.exists %}
                    <!-- 多学生场景渲染(取第一个为例,可循环所有学生) -->
                    {% with student=schedule.students.first %}
                    <td>{{ student.user.username }}</td>
                    <td>{{ schedule.duration }}</td>
                    <td>{{ student.studentId }}</td>
                    <td>{{ student.englishName }}</td>
                    {% endwith %}
                {% else %}
                    <td colspan="4">No student enrolled</td>
                {% endif %}
                <td>
                    {% if schedule.student or schedule.students.exists %}
                        Scheduled
                    {% else %}
                        Available
                    {% endif %}
                </td>
                <td>
                    {% if schedule.student %}
                        <a href="{% url 'student_profile' schedule.student.id %}">View</a>
                    {% elif schedule.students.exists %}
                        <a href="{% url 'schedule_students' schedule.id %}">View All</a>
                    {% endif %}
                </td>
            </tr>
            {% empty %}
            <tr>
                <td colspan="7">No schedules for today</td>
            </tr>
            {% endfor %}
        </table>
    </div>
</div>
{% endblock content %}

四、额外排查步骤

  • 验证选课逻辑:检查学生选课代码是否正确将Student实例关联到Schedule,例如:
    # 一对一场景选课
    schedule = Schedule.objects.get(id=schedule_id)
    if not schedule.student and schedule.capacity > 0:
        schedule.student = request.user.student
        schedule.save()
    
    # 多学生场景选课
    schedule = Schedule.objects.get(id=schedule_id)
    if schedule.students.count() < schedule.capacity:
        schedule.students.add(request.user.student)
    
  • 数据库数据检查:通过Django Admin或shell查看Schedule表的关联字段(student_id或students中间表)是否有有效值,确认关联已保存。
  • 权限验证:确保教师用户有权限访问关联的Student数据,无额外权限限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:15:33