30-课程详情页之后台

课程详情页之后台

一、流程

'''
1. 课程单查
	CourseView配置RetrieveModelMixin
2. 课程章节
	新建视图中 CourseChapterView, 继承G/L
	新建序列化 CourseChapterModelSerializer
		需要的字段. name, summary, chapter, 
		章节下的课时使用子序列化. 新建序列化 CourseSectionModelSerializer
			需要的字段name, orders, duration, section_type_name, section_link, free_trail
	配置路由 course_chapter		
	问题: 会把所有的章节查出来
		解决: 按照课程过滤
	问题: 前端的章节使用的路由与刚刚写的不匹配
		解决: 修改后端路由为 chapters
'''

二、路由:course/urls.py

router.register('free', views.CourseView, 'free')
router.register('chapters', views.CourseChapterView, 'chapters')

三、视图:course/views.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (
    ListModelMixin, RetrieveModelMixin
)

from .models import (
    CourseCategory, Course, CourseChapter
)
from .serializer import (
    CourseCategoryModelSerializer, CourseModelSerializer, CourseChapterModelSerializer
)

# 课程群查
from .pagination import PageNumberPagination
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters.rest_framework import DjangoFilterBackend


class CourseView(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseModelSerializer
    pagination_class = PageNumberPagination

    filter_backends = []
    # 内置排序
    filter_backends.append(OrderingFilter)
    ordering_param = 'ordering'
    ordering_fields = ('id', 'price', 'students')

    # django-filter过滤
    filter_backends.append(DjangoFilterBackend)
    # 指定过滤字段方式一:
    filter_fields = ['course_category', 'students']
    
    
# 一个课程的所有章节(群查)
class CourseChapterView(ListModelMixin, GenericViewSet):
    queryset = CourseChapter.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseChapterModelSerializer

    # 课程章节按照每个课程进行过滤
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']

四、序列化:course/serializer.py

class CourseSectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CourseSection
        fields = ('name', 'orders', 'section_link', 'duration', 'free_trail')


class CourseChapterSerializer(serializers.ModelSerializer):
    coursesections = CourseSectionSerializer(many=True)
    class Meta:
        model = models.CourseChapter
        fields = ('name', 'chapter', 'summary', 'coursesections')
上一篇:python网络编程 day40 数据库——连表查询和子查询


下一篇:hive学习总结