路飞-后台课程接口

课程接口修订

路由:course/urls.py
path("category/", views.CategoryListAPIView.as_view()),
path("", views.CourseListAPIView.as_view()),
视图:course/views.py
from rest_framework.generics import ListAPIView

from . import models, serializers

class CategoryListAPIView(ListAPIView):
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = serializers.CategoryModelSerializer


from .paginations import CoursePageNumberPagination
from rest_framework.filters import OrderingFilter
# 安装django-filter,注册django_filters
from django_filters.rest_framework import DjangoFilterBackend
class CourseListAPIView(ListAPIView):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True)
    serializer_class = serializers.CourseModelSerializer
    # 分页
    pagination_class = CoursePageNumberPagination
    #
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    ordering_fields = ('id', 'price', 'students')
    filter_fields = ('course_category', )
分页:paginations.py
class CoursePageNumberPagination(PageNumberPagination):
    """课程列表数据的分页器"""
    page_query_param = 'page'
    page_size_query_param = 'page_size'
    page_size = 2
    max_page_size = 10
模型:course/models.py
class Course(BaseModel):
    # ...
    # 连表查询
    @property
    def section_list(self):
        temp_section_list = []

        for chapter in self.coursechapters.all():
            for section in chapter.coursesections.all():
                # 最多需要4条数据
                if len(temp_section_list) >= 4:
                    return temp_section_list
                temp_section_list.append({
                    'free_trail': section.free_trail,
                    'name': section.name
                })
        return temp_section_list
序列化:course/serializers.py
from rest_framework.serializers import ModelSerializer

from . import models

class CategoryModelSerializer(ModelSerializer):
    class Meta:
        model = models.CourseCategory
        fields = ('id', 'name')

class TeacherModelSerializer(ModelSerializer):
    class Meta:
        model = models.Teacher
        fields = ('name', 'role', 'title', 'signature', 'image', 'brief')

class CourseModelSerializer(ModelSerializer):
    teacher = TeacherModelSerializer()
    class Meta:
        model = models.Course
        fields = (
            'id',
            'name',
            'course_img',
            'brief',
            'period',
            'attachment_path',
            'students',
            'sections',
            'pub_sections',
            'price',
            'teacher',
            'section_list',
        )
posted @ 2019-11-12 19:54  竣~  阅读(93)  评论(0编辑  收藏  举报