路由:course/urls.py
router.register('categories', views.CourseCategoryViewSet, 'categories') # 分类
router.register('free', views.CourseViewSet, 'free') # 课程
视图:course/views.py
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from . import models, serializers
# 课程分类群查
class CourseCategoryViewSet(GenericViewSet, ListModelMixin):queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).all()serializer_class = serializers.CourseCategorySerializer# 课程群查# 分页组件:基础分页(采用)、偏移分页、游标分页(了解)
from . import pagination# 过滤组件:搜索功能、排序功能
from rest_framework.filters import SearchFilter, OrderingFilter# django-filter插件:分类功能
from django_filters.rest_framework import DjangoFilterBackend
from .filters import CourseFilterSet# 前台携带所有过滤规则的请求url:
# http://127.0.0.1:8000/course/free/?page=1&page_size=10&search=python&ordering=-price&min_price=30&count=1
class CourseViewSet(GenericViewSet, ListModelMixin):queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()serializer_class = serializers.CourseSerializer# 分页组件pagination_class = pagination.PageNumberPagination# 过滤组件:实际开发,有多个过滤条件时,要把优先级高的放在前面filter_backends = [SearchFilter, OrderingFilter, DjangoFilterBackend]# 参与搜索的字段search_fields = ['name', 'id', 'brief']# 允许排序的字段ordering_fields = ['id', 'price', 'students']# 过滤类:分类过滤、区间过滤filter_class = CourseFilterSet
分类区间过滤:filters.py
# django-filter插件 过滤类
from django_filters.filterset import FilterSet
from . import models
from django_filters import filters
class CourseFilterSet(FilterSet):# 区间过滤:field_name关联的Model字段;lookup_expr设置规则;gt是大于,gte是大于等于;min_price = filters.NumberFilter(field_name='price', lookup_expr='gte')max_price = filters.NumberFilter(field_name='price', lookup_expr='lte')class Meta:model = models.Course# 如果过滤条件仅仅就是Model已有的字段,方式一更好# 但是方式二可以自定义过滤字段fields = ['course_category', 'min_price', 'max_price']
from rest_framework.pagination import PageNumberPagination as DrfPageNumberPaginationclass PageNumberPagination(DrfPageNumberPagination):# 默认一页显示的条数page_size = 2# url中携带页码的keypage_query_param = 'page'# url中用户携带自定义一页条数的keypage_size_query_param = 'page_size'# 用户最大可自定义一页的条数max_page_size = 10
模型:course/models.py
class Course(BaseModel):# ...@propertydef course_type_name(self):return self.get_course_type_display()@propertydef level_name(self):return self.get_level_display()@propertydef status_name(self):return self.get_status_display()# 连表序列化字段@propertydef section_list(self):# 检索所以章节所以课时,返回前4课时,不足4课时全部返回temp_section_list = []for chapter in self.coursechapters.all():for section in chapter.coursesections.all():temp_section_list.append({'name': section.name,'section_link': section.section_link,'duration': section.duration,'free_trail': section.free_trail,})if len(temp_section_list) >= 4:return temp_section_list # 最多4条return temp_section_list # 不足4条class Teacher(BaseModel):# ...@propertydef role_name(self):return self.get_role_display()
序列化:course/serializers.py
from rest_framework import serializers
from . import models
class CourseCategorySerializer(serializers.ModelSerializer):class Meta:model = models.CourseCategoryfields = ('id', 'name')# 子序列化
class TeacherSerializer(serializers.ModelSerializer):class Meta:model = models.Teacherfields = ('name', 'role_name', 'title', 'signature', 'image', 'brief')class CourseSerializer(serializers.ModelSerializer):teacher = TeacherSerializer(many=False)class Meta:model = models.Coursefields = ('id','name','course_img','brief','attachment_path','pub_sections','price','students','period','sections','course_type_name','level_name','status_name','teacher','section_list',)