11. 开发学生选课功能
SQL
CREATE TABLE `student_course` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'ID',
`student_id` int DEFAULT NULL COMMENT '学生ID',
`course_id` int DEFAULT NULL COMMENT '课程ID',
`year` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '学年',
`status` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '选课状态',
`check_status` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '审核状态',
`time` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '选课时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='选课信息';
登录返回学生的专业 ID
# 登录
@api_router.post("/login")
async def login(account: Account):
if account.role == '管理员':
admin = await Admin.get_or_none(username=account.username)
if admin is None:
raise CustomException("账号或密码错误")
if admin.password != account.password:
raise CustomException("账号或密码错误")
account = Account.model_validate(admin)
elif account.role == '学生':
student = await Student.get_or_none(username=account.username).prefetch_related("clazz__major")
if student is None:
raise CustomException("账号或密码错误")
if student.password != account.password:
raise CustomException("账号或密码错误")
account = Account.model_validate(student)
account.clazzId = student.clazz.id if student and student.clazz else None
account.majorId = student.clazz.major.id if student and student.clazz and student.clazz.major else None
else:
raise CustomException("角色错误")
return Result.success(account)
个人资料里面的表单
<el-form-item label="所属班级" prop="clazzId" v-if="data.user.role === '学生'">
<el-select disabled placeholder="请选择班级" v-model="data.user.clazzId">
<el-option v-for="item in data.classList" :key="item.id" :label="item.name" :value="item.id"></el-option>
</el-select>
</el-form-item>
<el-form-item label="所属专业" v-if="data.user.role === '学生'">
<el-select disabled v-model="data.user.majorId">
<el-option v-for="item in data.majorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
</el-select>
</el-form-item>
后端接口
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from pydantic import create_model, BaseModel, Field
from tortoise.contrib.pydantic import pydantic_model_creator
from common.exception_handler import CustomException
from common.result import Result, PageInfo
from models import StudentCourse
router = APIRouter(prefix="/studentCourse")
StudentCoursePydantic = pydantic_model_creator(StudentCourse)
StudentCourseCreatePydantic = create_model(
"StudentCourseCreatePydantic",
**{
name: (Optional[field.annotation], None)
for name, field in StudentCoursePydantic.model_fields.items()
},
student_id=(Optional[int], Field(None, alias="studentId")),
course_id=(Optional[int], Field(None, alias="courseId")),
)
# 新增
@router.post("/add")
async def add(student_course_create_pydantic: StudentCourseCreatePydantic):
# 当前的这个学生是否有已选的课程
db_student_course = await (StudentCourse.filter(student_id=student_course_create_pydantic.student_id)
.filter(course_id=student_course_create_pydantic.course_id)
.filter(status__not='已退').filter(status__not='未选中')
.first())
if db_student_course is not None:
raise CustomException("该课程已被选")
student_course_create_pydantic.time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 将参数转换成 字典数据
create_data = student_course_create_pydantic.model_dump(exclude_unset=True, exclude={"id"})
await StudentCourse.create(**create_data) # no=xxx,name=xxx,college=xxx
return Result.success()
# 更新
@router.put("/update")
async def add(student_course_create_pydantic: StudentCourseCreatePydantic):
if student_course_create_pydantic.id is None:
raise CustomException("缺少参数ID")
if student_course_create_pydantic.checkStatus == '通过':
student_course_create_pydantic.status = '已选'
elif student_course_create_pydantic.checkStatus == '拒绝':
student_course_create_pydantic.status = '未选中'
# 将参数转换成 字典数据
update_data = student_course_create_pydantic.model_dump(exclude_unset=True, exclude={"id"})
await StudentCourse.filter(id=student_course_create_pydantic.id).update(
**update_data) # no=xxx,name=xxx,college=xxx where id = xxx
return Result.success()
# 删除
@router.delete('/delete/{student_course_id}')
async def delete(student_course_id: int):
await StudentCourse.filter(id=student_course_id).delete()
return Result.success()
# 单个查询
@router.get('/selectById/{student_course_id}')
async def select_by_id(student_course_id: int):
studentCourse = await StudentCourse.get_or_none(id=student_course_id)
return Result.success(studentCourse)
# 查询所有数据
@router.get('/selectAll')
async def select_all(name: str = ""):
studentCourse_list = await StudentCourse.filter(name__contains=name) # name__contains表示根据name进行模糊查询
return Result.success(studentCourse_list)
# 分页查询数据
@router.get('/selectPage')
async def select_page(studentName: str = "", courseName: str = "", studentId: int = 0, pageNum: int = 1, pageSize: int = 10):
# prefetch_related 关联查询到 major模块的数据
query = StudentCourse.all().prefetch_related("course", "student")
if studentName != "":
query = query.filter(student__name__contains=studentName)
if courseName != "":
query = query.filter(course__name__contains=courseName)
if studentId > 0:
query = query.filter(student__id=studentId)
student_course_list = await query.offset((pageNum - 1) * pageSize).limit(pageSize)
total = await query.count()
student_course_dict_list = [
{
**StudentCoursePydantic.model_validate(student_course).model_dump(), # id=xxx,no=xxx,name=xxx
"studentName": student_course.student.name if student_course.student else None,
"courseName": student_course.course.name if student_course.course else None
}
for student_course in student_course_list
]
page_info = PageInfo(list=student_course_dict_list, total=total)
return Result.success(page_info)
前端页面
<template>
<div>
<div class="card" style="margin-bottom: 5px;">
<el-input v-model="data.courseName" style="width: 300px; margin-right: 10px" placeholder="请输入课程名称查询"></el-input>
<el-input v-if="data.user.role === '管理员'" v-model="data.studentName" style="width: 300px; margin-right: 10px" placeholder="请输入学生名称查询"></el-input>
<el-button type="primary" @click="load">查询</el-button>
<el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
</div>
<div class="card" style="margin-bottom: 5px">
<div style="margin-bottom: 10px" v-if="data.user.role === '学生'">
<el-button type="primary" @click="handleAdd" >新增选课</el-button>
</div>
<el-table :data="data.tableData" stripe>
<el-table-column label="课程名称" prop="courseName"></el-table-column>
<el-table-column label="学生" prop="studentName"></el-table-column>
<el-table-column label="学年" prop="year"></el-table-column>
<el-table-column label="选课状态" prop="status">
<template #default="scope">
<el-tag type="warning" v-if="scope.row.status === '申请中'">申请中</el-tag>
<el-tag type="success" v-if="scope.row.status === '已选'">已选</el-tag>
<el-tag type="danger" v-if="scope.row.status === '已退'">已退</el-tag>
<el-tag type="danger" v-if="scope.row.status === '未选中'">未选中</el-tag>
</template>
</el-table-column>
<el-table-column label="审核状态" prop="checkStatus">
<template #default="scope">
<el-tag type="warning" v-if="scope.row.checkStatus === '待审核'">待审核</el-tag>
<el-tag type="success" v-if="scope.row.checkStatus === '通过'">通过</el-tag>
<el-tag type="danger" v-if="scope.row.checkStatus === '拒绝'">拒绝</el-tag>
</template>
</el-table-column>
<el-table-column label="选课时间" prop="time"></el-table-column>
<el-table-column label="审核" align="center" width="160" v-if="data.user.role === '管理员'">
<template #default="scope">
<el-button type="primary" :disabled="scope.row.checkStatus === '通过'" @click="updateCheckStatus(scope.row, '通过')">通过</el-button>
<el-button type="danger" :disabled="scope.row.checkStatus === '拒绝'" @click="updateCheckStatus(scope.row, '拒绝')">拒绝</el-button>
</template>
</el-table-column>
<el-table-column label="操作" align="center" width="160">
<template #default="scope">
<el-button type="primary" v-if="data.user.status === '已选'">退课</el-button>
<el-button type="danger" @click="handleDelete(scope.row.id)" v-if="data.user.role === '管理员'">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="card">
<el-pagination @current-change="load" background layout="total, prev, pager, next" v-model:page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"/>
</div>
<el-dialog title="选课信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
<el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="100px" style="padding-right: 50px">
<el-form-item prop="courseId" label="课程">
<el-select placeholder="请选择课程" v-model="data.form.courseId">
<el-option v-for="item in data.courseList" :key="item.id" :label="item.name" :value="item.id"></el-option>
</el-select>
</el-form-item>
<el-form-item label="学年" prop="year">
<el-radio-group v-model="data.form.year">
<el-radio-button v-for="item in ['2025-2026', '2026-2027', '2027-2028']" :key="item" :label="item" :value="item"></el-radio-button>
</el-radio-group>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="data.formVisible = false">取 消</el-button>
<el-button type="primary" @click="save">保 存</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script setup>
import request from "@/utils/request";
import {reactive, ref} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
const formRef = ref()
const data = reactive({
user: JSON.parse(localStorage.getItem('system-user') || '{}'),
pageNum: 1,
pageSize: 10,
total: 0,
formVisible: false,
form: {},
tableData: [],
courseList: [],
courseName: null,
studentName: null,
rules: {
courseId: [
{ required: true, message: '请选择课程', trigger: 'change' }
],
year: [
{ required: true, message: '请现在学年', trigger: 'change' }
],
}
})
// 查询课程的信息list
request.get('/course/selectAll', {
params: {
majorId: data.user.majorId
}
}).then(res => {
data.courseList = res.data
})
// 分页查询
const load = () => {
request.get('/studentCourse/selectPage', {
params: {
pageNum: data.pageNum,
pageSize: data.pageSize,
courseName: data.courseName,
studentName: data.studentName,
studentId: data.user.role === '管理员' ? null : data.user.id
}
}).then(res => {
if (res.code === '200') {
data.tableData = res.data?.list
data.total = res.data?.total
} else {
ElMessage.error(res.msg)
}
})
}
load()
// 新增
const handleAdd = () => {
data.form = {}
data.formVisible = true
}
// 编辑
const handleEdit = (row) => {
data.form = JSON.parse(JSON.stringify(row))
data.formVisible = true
}
// 新增保存
const add = () => {
data.form.studentId = data.user.id
data.form.status = '申请中'
data.form.checkStatus = '待审核'
request.post('/studentCourse/add', data.form).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
data.formVisible = false
} else {
ElMessage.error(res.msg)
}
})
}
const updateCheckStatus = (row, checkStatus) => {
ElMessageBox.confirm('您确定审核' + checkStatus + "吗?", '审核确认', { type: 'warning' }).then(res => {
row.checkStatus = checkStatus
request.put('/studentCourse/update', row).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
} else {
ElMessage.error(res.msg)
}
})
}).catch(err=>{})
}
// 编辑保存
const update = () => {
request.put('/studentCourse/update', data.form).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
data.formVisible = false
} else {
ElMessage.error(res.msg)
}
})
}
// 弹窗保存
const save = () => {
formRef.value.validate(valid => {
if (valid) {
// data.form有id就是更新,没有就是新增
data.form.id ? update() : add()
}
})
}
// 删除
const handleDelete = (id) => {
ElMessageBox.confirm('删除后数据无法恢复,您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
request.delete('/studentCourse/delete/' + id).then(res => {
if (res.code === '200') {
load()
ElMessage.success('操作成功')
} else {
ElMessage.error(res.msg)
}
})
}).catch(err => {})
}
// 重置
const reset = () => {
data.courseName = null
data.studentName = null
load()
}
</script>