课程功能后端

课程功能后端

表分析

# 轻课 实战课 免费课    需要几个表
	所有课程使用一个表通过类型区分,但是可能出现字段不一样,数据量越来越多,导致表查询速度慢
    选择:一种课程一个表
    
    
# 实战课线---》分析出5张表
	-课程分类表   一个分类下有多个课程跟课程一对多
	-实战课表    一个实战课,会有多个章节,跟章节一对多
    -章节表     一个章节下有多个课时,章节和课时一对多
    -课时表
    -老师表     跟实战课一对多
    
    
    -正常课程 有评论,需要建立评论表,评论板块没写,这个表就不写了

新建课程course.app

切换至项目下apps目录
python ../../manage.py startapp course
"创建完了注意去注册"

models

from django.db import models
from utils.common_model import BaseModel


# Create your models here.
# 5张:课程分类,实战课,章节,课时,老师表


# 课程分类表
class CourseCategory(BaseModel):
    """分类"""
    name = models.CharField(max_length=64, unique=True, verbose_name="分类名称")

    class Meta:
        db_table = "luffy_course_category"
        verbose_name = "分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s" % self.name


# 实战课表
class Course(BaseModel):
    """课程"""
    course_type = (
        (0, '付费'),
        (1, 'VIP专享'),
        (2, '学位课程')
    )
    level_choices = (
        (0, '初级'),
        (1, '中级'),
        (2, '高级'),
    )
    status_choices = (
        (0, '上线'),
        (1, '下线'),
        (2, '预上线'),
    )
    name = models.CharField(max_length=128, verbose_name="课程名称")
    course_img = models.ImageField(upload_to="courses", max_length=255, verbose_name="封面图片", blank=True, null=True)
    course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型")
    brief = models.TextField(max_length=2048, verbose_name="详情介绍", null=True, blank=True)
    level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name="难度等级")
    pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True)
    period = models.IntegerField(verbose_name="建议学习周期(day)", default=7)
    attachment_path = models.FileField(upload_to="attachment", max_length=128, verbose_name="课件路径", blank=True,null=True)
    status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态")

    students = models.IntegerField(verbose_name="学习人数", default=0) # 跟用户表做关联,优化字段

    sections = models.IntegerField(verbose_name="总课时数量", default=0)
    pub_sections = models.IntegerField(verbose_name="课时更新数量", default=0)
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="课程原价", default=0)

    # on_delete 级联删除,出了级联删除外,还有 很多其他的,暂时先不讲
    teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授课老师")
    course_category = models.ForeignKey("CourseCategory", on_delete=models.SET_NULL, db_constraint=False, null=True,blank=True, verbose_name="课程分类")
    class Meta:
        db_table = "luffy_course"
        verbose_name = "课程"
        verbose_name_plural = "课程"

    def __str__(self):
        return "%s" % self.name


# 章节表
class CourseChapter(BaseModel):
    """章节"""
    # 章节跟课程一对多,关联字段写在多的一方
    # related_name 暂时先不讲
    course = models.ForeignKey("Course", related_name='coursechapters', on_delete=models.CASCADE, verbose_name="课程名称")
    chapter = models.SmallIntegerField(verbose_name="第几章", default=1)
    name = models.CharField(max_length=128, verbose_name="章节标题")
    summary = models.TextField(verbose_name="章节介绍", blank=True, null=True)
    pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True)

    class Meta:
        db_table = "luffy_course_chapter"
        verbose_name = "章节"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s:(第%s章)%s" % (self.course, self.chapter, self.name)


# 课时表
class CourseSection(BaseModel):
    """课时"""
    section_type_choices = (
        (0, '文档'),
        (1, '练习'),
        (2, '视频')
    )
    # 课时跟章节一对多,关联写段写在多的一方
    chapter = models.ForeignKey("CourseChapter", related_name='coursesections', on_delete=models.CASCADE,verbose_name="课程章节")
    name = models.CharField(max_length=128, verbose_name="课时标题")
    orders = models.PositiveSmallIntegerField(verbose_name="课时排序")
    section_type = models.SmallIntegerField(default=2, choices=section_type_choices, verbose_name="课时种类")
    section_link = models.CharField(max_length=255, blank=True, null=True, verbose_name="课时链接",help_text="若是video,填vid,若是文档,填link")
    duration = models.CharField(verbose_name="视频时长", blank=True, null=True, max_length=32)  # 仅在前端展示使用
    pub_date = models.DateTimeField(verbose_name="发布时间", auto_now_add=True)
    free_trail = models.BooleanField(verbose_name="是否可试看", default=False)

    class Meta:
        db_table = "luffy_course_section"
        verbose_name = "课时"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s-%s" % (self.chapter, self.name)


# 老师表
class Teacher(BaseModel):
    """导师"""
    role_choices = (
        (0, '讲师'),
        (1, '导师'),
        (2, '班主任'),
    )
    name = models.CharField(max_length=32, verbose_name="导师名")
    role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="导师身份")
    title = models.CharField(max_length=64, verbose_name="职位、职称")
    signature = models.CharField(max_length=255, verbose_name="导师签名", help_text="导师签名", blank=True, null=True)
    image = models.ImageField(upload_to="teacher", null=True, verbose_name="导师封面")
    brief = models.TextField(max_length=1024, verbose_name="导师描述")

    class Meta:
        db_table = "luffy_teacher"
        verbose_name = "导师"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s" % self.name

    
    
    
    # 执行迁移命令

表数据录入

INSERT INTO luffy_teacher(id, orders, is_show, is_delete, created_time, updated_time, name, role, title, signature, image, brief) VALUES (1, 1, 1, 0, '2022-07-14 13:44:19.661327', '2022-07-14 13:46:54.246271', 'Alex', 1, '老男孩Python教学总监', '金角大王', 'teacher/alex_icon.png', '老男孩教育CTO & CO-FOUNDER 国内知名PYTHON语言推广者 51CTO学院2016\2017年度最受学员喜爱10大讲师之一 多款开源软件作者 曾任职公安部、飞信、中金公司、NOKIA中国研究院、华尔街英语、ADVENT、汽车之家等公司');

INSERT INTO luffy_teacher(id, orders, is_show, is_delete, created_time, updated_time, name, role, title, signature, image, brief) VALUES (2, 2, 1, 0, '2022-07-14 13:45:25.092902', '2022-07-14 13:45:25.092936', 'Mjj', 0, '前美团前端项目组架构师', NULL, 'teacher/mjj_icon.png', '是马JJ老师, 一个集美貌与才华于一身的男人,搞过几年IOS,又转了前端开发几年,曾就职于美团网任高级前端开发,后来因为不同意王兴(美团老板)的战略布局而出家做老师去了,有丰富的教学经验,开起车来也毫不含糊。一直专注在前端的前沿技术领域。同时,爱好抽烟、喝酒、烫头(锡纸烫)。 我的最爱是前端,因为前端妹子多。');

INSERT INTO luffy_teacher(id, orders, is_show, is_delete, created_time, updated_time, name, role, title, signature, image, brief) VALUES (3, 3, 1, 0, '2022-07-14 13:46:21.997846', '2022-07-14 13:46:21.997880', 'Lyy', 0, '老男孩Linux学科带头人', NULL, 'teacher/lyy_icon.png', 'Linux运维技术专家,老男孩Linux金牌讲师,讲课风趣幽默、深入浅出、声音洪亮到爆炸');
-- 分类表
INSERT INTO luffy_course_category(id, orders, is_show, is_delete, created_time, updated_time, name) VALUES (1, 1, 1, 0, '2022-07-14 13:40:58.690413', '2022-07-14 13:40:58.690477', 'Python');

INSERT INTO luffy_course_category(id, orders, is_show, is_delete, created_time, updated_time, name) VALUES (2, 2, 1, 0, '2022-07-14 13:41:08.249735', '2022-07-14 13:41:08.249817', 'Linux');
-- 课程表
INSERT INTO luffy_course(id, orders, is_show, is_delete, created_time, updated_time, name, course_img, course_type, brief, level, pub_date, period, attachment_path, status, students, sections, pub_sections, price, course_category_id, teacher_id) VALUES (1, 1, 1, 0, '2022-07-14 13:54:33.095201', '2022-07-14 13:54:33.095238', 'Python开发21天入门', 'courses/alex_python.png', 0, 'Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土', 0, '2022-07-14', 21, '', 0, 231, 120, 120, 0.00, 1, 1);

INSERT INTO luffy_course(id, orders, is_show, is_delete, created_time, updated_time, name, course_img, course_type, brief, level, pub_date, period, attachment_path, status, students, sections, pub_sections, price, course_category_id, teacher_id) VALUES (2, 2, 1, 0, '2022-07-14 13:56:05.051103', '2022-07-14 13:56:05.051142', 'Python项目实战', 'courses/mjj_python.png', 0, '', 1, '2022-07-14', 30, '', 0, 340, 120, 120, 99.00, 1, 2);

INSERT INTO luffy_course(id, orders, is_show, is_delete, created_time, updated_time, name, course_img, course_type, brief, level, pub_date, period, attachment_path, status, students, sections, pub_sections, price, course_category_id, teacher_id) VALUES (3, 3, 1, 0, '2022-07-14 13:57:21.190053', '2022-07-14 13:57:21.190095', 'Linux系统基础5周入门精讲', 'courses/lyy_linux.png', 0, '', 0, '2022-07-14', 25, '', 0, 219, 100, 100, 39.00, 2, 3);
-- 章节表
INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (1, 1, 1, 0, '2022-07-14 13:58:34.867005', '2022-07-14 14:00:58.276541', 1, '计算机原理', '', '2022-07-14', 1);

INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (2, 2, 1, 0, '2022-07-14 13:58:48.051543', '2022-07-14 14:01:22.024206', 2, '环境搭建', '', '2022-07-14', 1);

INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (3, 3, 1, 0, '2022-07-14 13:59:09.878183', '2022-07-14 14:01:40.048608', 1, '项目创建', '', '2022-07-14', 2);

INSERT INTO luffy_course_chapter(id, orders, is_show, is_delete, created_time, updated_time, chapter, name, summary, pub_date, course_id) VALUES (4, 4, 1, 0, '2022-07-14 13:59:37.448626', '2022-07-14 14:01:58.709652', 1, 'Linux环境创建', '', '2022-07-14', 3);
-- 课时表
INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (1, 1, 0, '2022-07-14 14:02:33.779098', '2022-07-14 14:02:33.779135', '计算机原理上', 1, 2, NULL, NULL, '2022-07-14 14:02:33.779193', 1, 1);

INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (2, 1, 0, '2022-07-14 14:02:56.657134', '2022-07-14 14:02:56.657173', '计算机原理下', 2, 2, NULL, NULL, '2022-07-14 14:02:56.657227', 1, 1);

INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (3, 1, 0, '2022-07-14 14:03:20.493324', '2022-07-14 14:03:52.329394', '环境搭建上', 1, 2, NULL, NULL, '2022-07-14 14:03:20.493420', 0, 2);

INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (4, 1, 0, '2022-07-14 14:03:36.472742', '2022-07-14 14:03:36.472779', '环境搭建下', 2, 2, NULL, NULL, '2022-07-14 14:03:36.472831', 0, 2);

INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (5, 1, 0, '2022-07-14 14:04:19.338153', '2022-07-14 14:04:19.338192', 'web项目的创建', 1, 2, NULL, NULL, '2022-07-14 14:04:19.338252', 1, 3);

INSERT INTO luffy_course_Section(id, is_show, is_delete, created_time, updated_time, name, orders, section_type, section_link, duration, pub_date, free_trail, chapter_id) VALUES (6, 1, 0, '2022-07-14 14:04:52.895855', '2022-07-14 14:04:52.895890', 'Linux的环境搭建', 1, 2, NULL, NULL, '2022-07-14 14:04:52.895942', 1, 4);

课程分类接口

视图

from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import GenericViewSet
from .models import CourseCategory
from .serializer import CourseCategorySerializer
from utils.common_mixin import CommonListModelMixin

# 查询所有课程分类接口
class CourseCategoryView(GenericViewSet,CommonListModelMixin):
    queryset = CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseCategorySerializer

序列化类

from rest_framework import serializers
from .models import CourseCategory
# 查看课程分类序列化类
class CourseCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseCategory
        fields = ['id', 'name']

路由注册

# 记住去一下总路由分发
from rest_framework.routers import SimpleRouter
from .views import CourseCategoryView
router = SimpleRouter()
# 访问 http://127.0.0.1:8001/api/v1/course/category/ 查询所有分类
router.register('category', CourseCategoryView, 'category')
urlpatterns = [

]
urlpatterns += router.urls

查询所有课程接口(过滤,排序)

视图类

from rest_framework.viewsets import GenericViewSet
from .models import CourseCategory,Course
from .serializer import CourseCategorySerializer,CourseSerializer
from utils.common_mixin import CommonListModelMixin
# 分页自己重写
from utils.common_page import CommonPageNumberPagination
# 排序
from rest_framework.filters import OrderingFilter
# 过滤
from django_filters.rest_framework import DjangoFilterBackend

# 查询所有课程接口
class CourseView(GenericViewSet,CommonListModelMixin):
    queryset = Course.objects.filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 分页 需要重写
    pagination_class = CommonPageNumberPagination
    # 排序,过滤(需要下载django-filter)
    filter_backends = [OrderingFilter,DjangoFilterBackend]
    # 指定排序字段
    ordering_fields = ['price','students']
    # 指定过滤字段
    filterset_fields = ['course_category']

过滤

utlis.common_page

from rest_framework.pagination import PageNumberPagination

class CommonPageNumberPagination(PageNumberPagination):
    page_size = 2  # 每页显示2条
    page_query_param = 'page'  # page=10  查询第10页的数据
    page_size_query_param = 'size'  # page=10&size=5    查询第10页,每页显示5条
    max_page_size = 5  # 每页最大显示5条

序列化类

from rest_framework import serializers
from .models import CourseCategory, Course,Teacher

#子序列化 
class TeacherSerializer(serializers.ModelSerializer):
    # 子序列化
    class Meta:
        model = Teacher
        fields = [
            'id', 'name', 'role_name', 'title', 'signature', 'image', 'brief'
        ]
# 查看课程接口
class CourseSerializer(serializers.ModelSerializer):
    # 用子序列化
    teacher = TeacherSerializer()

    class Meta:
        model = Course
        fields = [
            'id',
            'name',
            'course_img',
            'brief',  # 课程介绍
            'attachment_path',  # 课程课件路径
            'pub_sections',  # 更新了多少课时
            'price',  # 价格
            'students',  # 学习人数
            'period',  # 建议学习周期
            'sections',  # 总课时数量

            'course_type_name',  # 定制返回格式,在序列化类中或表模型中写方法    表模型中写的方法
            'level_name',  # 等级名字
            'status_name',  # 课程状态

            'teacher',  # 老师 : 表模型中写    序列化类中   子序列化:给Teacher表写个序列化类
            'section_list',  # 表模型中写  (DDD:领域驱动模型 就是在表模型写)
        ]

在表模型中定制返回格式

class Course(BaseModel):
    """课程"""
    course_type = (
        (0, '付费'),
        (1, 'VIP专享'),
        (2, '学位课程')
    )
    level_choices = (
        (0, '初级'),
        (1, '中级'),
        (2, '高级'),
    )
    status_choices = (
        (0, '上线'),
        (1, '下线'),
        (2, '预上线'),
    )
    course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付费类型")
    level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name="难度等级")
    status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态")

    # 定制返回格式是个choise返回对应的文字
    def course_type_name(self):
        return self.get_course_type_display()

    def level_name(self):
        return self.get_level_display()

    def status_name(self):
        return self.get_status_display()

    def section_list(self):
        '''
              # 逻辑:
              #1 先根据课程,拿到所有章节
              #2 循环所有章节,拿出每个章节下的课时
              #3 拼到一个列表中
              # 4 判断一下列表长度是否大于等于四,直接 return
              '''
        l = []
        # 根据课程拿出所有章节,反向查询
        """外键字段 related_name属性
        related_name =coursechapters 可以用对象直接点coursechapters.all() 
        不需要在小写coursechapter_set.all() 拿数据想用这种set.all拿数据必须取消外键字段 related_name属性
        """
        course_chapter_list = self.coursechapters.all()
        # for循环章节拿出一个个章节对象
        for course_chapter in course_chapter_list:
            # 根据章节对象 拿出对应的课时
            course_section_list = course_chapter.coursesections.all()
            # 循环课时放到列表里返回到前端
            for course_section in course_section_list:
                # 返回课时名,课时链接,课时时长,课时是否可以试看
                l.append({'name': course_section.name, 'section_link': course_section.section_link,
                          'duration': course_section.duration, 'free_trail': course_section.free_trail})
                # 判断课时长度是否大于等于4,只返回4个或一下
                if len(l) >= 4:
                    return l
        # 里面条件不足4个也直接返回
        return l





class Teacher(BaseModel):
    def role_name(self):
        return self.get_role_display()

课程详情接口

查询所有课程接口返回的字段比较详细,课程详情也可以用。直接在查询课程接口上加一个查询单个mixin。

封装一下

utils.common_mixin

from rest_framework.mixins import RetrieveModelMixin


class CommonRetrieveModelMixin(RetrieveModelMixin):
    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

视图函数

from rest_framework.viewsets import GenericViewSet
from .models import CourseCategory,Course
from .serializer import CourseCategorySerializer,CourseSerializer
from utils.common_mixin import CommonListModelMixin,CommonRetrieveModelMixin
from utils.common_page import CommonPageNumberPagination
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend



# 查询所有课程接口
class CourseView(GenericViewSet,CommonListModelMixin,CommonRetrieveModelMixin):
    queryset = Course.objects.filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 分页 需要重写
    pagination_class = CommonPageNumberPagination
    # 排序,过滤(需要下载django-filter)
    filter_backends = [OrderingFilter,DjangoFilterBackend]
    # 指定排序字段
    ordering_fields = ['price','students']
    # 指定过滤字段
    filterset_fields = ['course_category']

查询所有章节接口

按课程过滤


# 查询所有章节接口
class CourseChapterView(GenericViewSet,CommonListModelMixin):
    queryset = CourseChapter.objects.filter(is_delete=False,is_show=True).order_by('orders')
    serializer_class = CourseChapterSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['course']

序列化类

class CourseSectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseSection
        # 课时名字,课时排序,课时视频链接,视频时长,是否免费
        fields=['id','name','orders','section_link','duration','free_trail']

# 查询章节序列化类
class CourseChapterSerializer(serializers.ModelSerializer):
    # 子序列化
    # 章节与课时是一对多关系所以many=True
    coursesections = CourseSectionSerializer(many=True)
    class Meta:
        model = CourseChapter
        # 章节名字,第几章, 章节介绍,章节下所有课程
        fields=['id','name','chapter','summary','coursesections']

路由

# http://127.0.0.1:8001/api/v1/course/coursechapter/ 查询章节
router.register('coursechapter', CourseChapterView, 'coursechapter')
posted @ 2023-03-10 17:27  李阿鸡  阅读(6)  评论(0编辑  收藏  举报
Title