• day81:luffy:课程分类页面&课程信息页面&指定分类显示课程信息&分页显示课程信息


    目录

    1.构建课程前端初始页面

    2.course后端的准备工作

    3.后端实现课程分类列表接口

    4.前端发送请求-获取课程分类信息

    5.后端实现课程列表信息的接口

    6.前端显示列表课程信息

    7.按照指定分类显示课程信息

    8.分页显示课程信息

    1.构建课程前端初始页面

    1.创建Course.Vue,并将初始样式代码放入vue文件中

    2.为course组件配置路由,用来做前端访问用的

    router/index.js

    import Vue from 'vue'
    import Router from 'vue-router'
    import Course from "@/components/Course"
    
    Vue.use(Router)
    
    export default new Router({
      mode:'history',
      routes: [
        ......
        {
          path: '/course',
          component: Course,
        }
      ]
    })

    2.course后端的准备工作

    1.在app下创建子应用course

    python3 ../../manage.py startapp course

    2.注册course应用

    INSTALLED_APPS = [
            ...
        'course',
    ]

    3.设计课程表结构

    models.py

    from django.db import models
    from luffyapi.utils.models import BaseModel
    # Create your models here.
    class CourseCategory(BaseModel):
        """
        课程分类
        """
        name = models.CharField(max_length=64, unique=True, verbose_name="分类名称")
        class Meta:
            db_table = "ly_course_category"
            verbose_name = "课程分类"
            verbose_name_plural = "课程分类"
    
    
        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="course", max_length=255, verbose_name="封面图片", blank=True, null=True)
        
        #费用类型字段是为了后期一些其他功能拓展用的,现在可以先不用,或者去掉它,目前我们项目用不到
        course_type = models.SmallIntegerField(choices=course_type,default=0, verbose_name="付费类型")
        # 这个字段是课程详情页里面展示的,并且详情介绍里面用户将来可能要上传一些图片之类的,所以我们会潜入富文本编辑器,让用户填写数据的时候可以上传图片啊、写标题啊、css、html等等内容
        brief = models.TextField(max_length=2048, verbose_name="详情介绍", null=True, blank=True)
        
        level = models.SmallIntegerField(choices=level_choices, default=1, verbose_name="难度等级")
        pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True)
        period = models.IntegerField(verbose_name="建议学习周期(day)", default=7)
        
        #课件资料的存放路径
        attachment_path = models.FileField(max_length=128, verbose_name="课件路径", blank=True, null=True)
        status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="课程状态")
        course_category = models.ForeignKey("CourseCategory", on_delete=models.CASCADE, null=True, blank=True,verbose_name="课程分类")
        students = models.IntegerField(verbose_name="学习人数",default = 0)
        lessons = models.IntegerField(verbose_name="总课时数量",default = 0)
        
        #总课时数量可能10个,但是目前之更新了3个,就跟小说、电视剧连载似的。
        pub_lessons = models.IntegerField(verbose_name="课时更新数量",default = 0)
        
        #课程原价
        price = models.DecimalField(max_digits=6,decimal_places=2, verbose_name="课程原价",default=0)
        teacher = models.ForeignKey("Teacher",on_delete=models.DO_NOTHING, null=True, blank=True,verbose_name="授课老师")
        class Meta:
            db_table = "ly_course"
            verbose_name = "专题课程"
            verbose_name_plural = "专题课程"
    
        def __str__(self):
            return "%s" % self.name
    
    
    
    class Teacher(BaseModel):
        """讲师、导师表"""
        role_choices = (
            (0, '讲师'),
            (1, '导师'),
            (2, '班主任'),
        )
        name = models.CharField(max_length=32, verbose_name="讲师title")
        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 = "ly_teacher"
            verbose_name = "讲师导师"
            verbose_name_plural = "讲师导师"
    
        def __str__(self):
            return "%s" % self.name
    
    
    class CourseChapter(BaseModel):
        """课程章节"""
        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 = "ly_course_chapter"
            verbose_name = "课程章节"
            verbose_name_plural = "课程章节"
    
        def __str__(self):
            return "%s:(第%s章)%s" % (self.course, self.chapter, self.name)
    
    
    class CourseLesson(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="课时排序") #在basemodel里面已经有了排序了
        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)
        course = models.ForeignKey('Course',related_name='course_lesson',verbose_name='课程',on_delete=models.CASCADE,null=True,blank=True)
        is_show_list = models.BooleanField(verbose_name='是否推荐到课程列表',default=False)
            lesson = models.IntegerField(verbose_name="第几课时")
        class Meta:
            db_table = "ly_course_lesson"
            verbose_name = "课程课时"
            verbose_name_plural = "课程课时"
    
        def __str__(self):
            return "%s-%s" % (self.chapter, self.name)

    4.执行数据库迁移

    python manage.py makemigrations
    python manage.py migrate

    5.把当前新增的课程模型注册到xadmin里面.

    courses/adminx.py

    import xadmin
    
    from .models import CourseCategory
    class CourseCategoryModelAdmin(object):
        """课程分类模型管理类"""
        pass
    xadmin.site.register(CourseCategory, CourseCategoryModelAdmin)
    
    
    from .models import Course
    class CourseModelAdmin(object):
        """课程模型管理类"""
        pass
    xadmin.site.register(Course, CourseModelAdmin)
    
    
    from .models import Teacher
    class TeacherModelAdmin(object):
        """老师模型管理类"""
        pass
    xadmin.site.register(Teacher, TeacherModelAdmin)
    
    
    from .models import CourseChapter
    class CourseChapterModelAdmin(object):
        """课程章节模型管理类"""
        pass
    xadmin.site.register(CourseChapter, CourseChapterModelAdmin)
    
    
    
    from .models import CourseLesson
    class CourseLessonModelAdmin(object):
        """课程课时模型管理类"""
        pass
    xadmin.site.register(CourseLesson, CourseLessonModelAdmin)

    3.后端实现课程分类列表接口

    1.添加课程分类的测试数据

    INSERT INTO `ly_course_category` (`id`,`orders`,`is_show`,`is_deleted`,`created_time`,`updated_time`,`name`)
     VALUES
    (1,11,1,0,'2019-08-13 07:08:47.100074','2019-08-13 07:44:05.903782','python'),
    (2,0,1,0,'2019-08-13 07:08:51.451093','2019-08-13 07:43:54.558940','go编程'),
    (3,3,1,0,'2019-08-13 07:08:57.390196','2019-08-13 07:08:57.390226','Linux运维'),
    (4,4,1,0,'2019-08-13 07:09:11.465963','2019-08-13 07:09:11.465994','前端开发'),(5,11,1,0,'2019-08-13 07:08:47.100074','2019-08-13 07:44:05.903782','php编程'),(6,0,1,0,'2019-08-13 07:08:51.451093','2019-08-13 07:43:54.558940','C/C++'),(7,3,1,0,'2019-08-13 07:08:57.390196','2019-08-13 07:08:57.390226','java web'),(8,4,1,0,'2019-08-13 07:09:11.465963','2019-08-13 07:09:11.465994','UI设计'),(9,11,1,0,'2019-08-13 07:09:11.465963','2019-08-13 07:09:11.465994','语文'),(10,145,2,0,'2019-08-13 07:09:11.465963','2019-08-13 07:09:11.465994','数学'),(11,1,2,0,'2019-08-13 07:09:11.465963','2019-08-13 07:09:11.465994','英语');

    2.为课程分类添加后端接口的路由,并编写视图函数和序列化器

    urls.py

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path(r'categorys/', views.CategoryView.as_view(),),
    
    ]

    views.py

    from . import models
    # Create your views here.
    from rest_framework.generics import ListAPIView
    from .serializers import CourseCategoryModelSerializer, CourseModelsSerializer
    
    
    class CategoryView(ListAPIView):
    
        queryset = models.CourseCategory.objects.filter(is_deleted=False,is_show=True)
        serializer_class = CourseCategoryModelSerializer

    serializers.py

    from rest_framework import serializers
    from . import models
    class CourseCategoryModelSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = models.CourseCategory
            fields = ['id', 'name']

    lyapi/urls.py

    urlpatterns = [
        ......
        path(r'course/',include('course.urls')),
    
    ]

    访问后端接口 /course/categorys 可查到分类数据

    4.前端发送请求-获取课程分类信息

    course.vue

    <!-- html -->
     <ul class="cate-list">
              <li class="title">课程分类:</li>
              <!-- 点击不同分类进行高亮效果的切换 --> 
              <li :class="{this:category===0}" @click="category=0">全部</li>
              <li v-for="(value, index) in category_list" :key="value.id" @click="category=value.id" :class="{this:category===value.id}">{{value.name}}</li>   
            </ul>
    // js
    <script>
        
      import Vheader from "./common/Vheader"
      import Footer from "./common/Footer"
      export default {
          name: "Course",
          data(){
            return{
              category:0,  //默认分类zhi
              category_list:[],
            }
          },
          components:{
            Vheader,
            Footer,
          },
    
          created() {
            this.$axios.get(`${this.$settings.Host}/course/categorys/`)
            .then((res)=>{
              console.log(res.data);
              this.category_list = res.data;
            })
          }
    
    
      }
    </script>

    此时在前端就可以看到课程分类的效果了

    5.后端实现课程列表信息的接口

    urls.py

    from django.urls import path
    from . import views
    
    urlpatterns = [
        ......
        path(r'courses/', views.CourseView.as_view(),),
    
    ]

    views.py

    from .serializers import CourseModelSerializer
    class CourseListAPIView(ListAPIView):
        queryset = Course.objects.filter(is_delete=False, is_show=True).order_by("orders")
        serializer_class = CourseModelSerializer

    添加一些测试数据

    INSERT INTO `ly_teacher` (`id`,`orders`,`is_show`,`is_deleted`,`created_time`,`updated_time`,`name`,`role`,`title`,`signature`,`image`,`brief`)
    VALUES 
    (1,1,1,0,'2019-08-13 07:13:01.531992','2019-08-13 07:13:01.532043','李老师',0,'xx公司技术总监','洪七公','teacher/logo2x.png','222');
    
    INSERT INTO `ly_course`
    (`id`,`orders`,`is_show`,`is_deleted`,`created_time`,`updated_time`,`name`,`course_img`,`course_type`,`brief`,`level`,`pub_date`,`period`,`attachment_path`,`status`,`students`,`lessons`,`pub_lessons`,`price`,`course_category_id`,`teacher_id`)
    VALUES
    (1,1,1,0,'2019-08-13 07:13:50.678948','2019-08-15 04:07:11.386224','flask框架','course/Loginbg.3377d0c.jpg',0,'<p>xxxx</p>',1,'2019-08-13',7,'README.md',0,99,110,110,1110.00,1,1),
    (2,2,1,0,'2019-08-13 07:15:32.490163','2019-08-15 04:13:22.430368','蘑菇街APP','course/course-cover.jpeg',0,'<p>dxxx</p>',2,'2019-08-13',7,'logo.svg',0,10,50,40,666.00,1,1),
    (3,3,1,0,'2019-08-13 07:15:32.490163','2019-08-20 10:49:41.880490','django框架','course/2.jpeg',0,'<p>dxxx</p>',1,'2019-08-13',7,'logo.svg',0,10,50,40,330.00,1,1),
    (15,4,1,0,'2019-08-13 07:15:32.490163','2019-08-13 07:15:32.490191','python入门','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,411.00,1,1),
    (16,5,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:28:04.791112','hbase入门','course/2.jpeg',0,'dxxx',1,'2019-08-13',7,'logo.svg',0,10,50,40,400.00,7,1),
    (17,6,1,0,'2019-08-13 07:15:32.490163','2019-08-13 07:15:32.490191','路飞学城项目实战','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,899.00,1,1),
    (18,7,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:29:47.667133','负载均衡','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,1088.00,6,1),
    (19,8,1,0,'2019-08-13 07:15:32.490163','2019-08-13 07:15:32.490191','MVC','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,1500.00,1,1),
    (20,9,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:28:52.126968','21天java入门','course/2.jpeg',0,'dxxx',0,'2019-08-13',7,'logo.svg',0,10,50,40,3000.00,7,1),
    (21,10,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:27:01.850049','7天玩转Linux运维','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,400.00,3,1),
    (22,11,1,0,'2019-08-13 07:15:32.490163','2019-08-13 07:15:32.490191','15天掌握flask框架','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,400.00,1,1),
    (23,12,1,0,'2019-08-13 07:15:32.490163','2019-08-13 07:23:56.015167','C编程嵌入式','course/2.jpeg',0,'dxxx',1,'2019-08-13',7,'logo.svg',0,10,50,40,399.00,3,1),
    (24,13,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:29:17.872840','3天玩转树莓派','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,400.00,3,1),
    (25,14,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:28:30.783768','MongoDB','course/2.jpeg',0,'dxxx',0,'2019-08-13',7,'logo.svg',0,10,50,40,400.00,3,1),
    (26,15,1,0,'2019-08-13 07:15:32.490163','2019-08-14 02:30:09.348192','Beego框架入门','course/2.jpeg',0,'dxxx',1,'2019-08-13',7,'logo.svg',0,10,50,40,699.00,2,1),
    (27,16,1,0,'2019-08-13 07:15:32.490163','2019-08-15 02:35:20.997672','beego框架进阶','course/2.jpeg',0,'<p>dxxx</p>',1,'2019-08-13',7,'logo.svg',0,10,50,50,400.00,2,1),
    (28,17,1,0,'2019-08-13 07:15:32.490163','2019-08-13 07:23:44.546598','以太坊入门','course/2.jpeg',0,'dxxx',2,'2019-08-13',7,'logo.svg',0,10,50,40,899.00,2,1),
    (29,18,1,0,'2019-08-13 07:15:32.490163','2019-08-15 04:05:10.421736','负载均衡','course/2.jpeg',0,'<div style="background:#eeeeee; border:1px solid #cccccc; padding:5px 10px"><span style="color:#16a085"><span style="font-family:Arial,Helvetica,sans-serif"><span style="font-size:28px"><span style="background-color:#f39c12">dxxx</span></span></span></span><img alt="" src="/media/2019/08/15/course-cover.jpeg" /></div>
    
    <div style="background:#eeeeee; border:1px solid #cccccc; padding:5px 10px">&nbsp;</div>
    
    <div style="background:#eeeeee; border:1px solid #cccccc; padding:5px 10px">
    <table border="1" cellpadding="1" cellspacing="1" style="500px">
        <tbody>
            <tr>
                <td>12321</td>
                <td>3232</td>
                <td>111</td>
            </tr>
            <tr>
                <td>33</td>
                <td>33</td>
                <td>22</td>
            </tr>
            <tr>
                <td>11</td>
                <td>22</td>
                <td>23</td>
            </tr>
        </tbody>
    </table>
    
    <p>&nbsp;</p>
    </div>',0,'2019-08-13',7,'logo.svg',0,10,50,40,400.00,3,1);

    serializers.py

    from rest_framework import serializers
    from . import models
    
    
    class CourseCategoryModelSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = models.CourseCategory
            fields = ['id', 'name']
    
    
    class TeacherModelSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.Teacher
            fields = ['name', 'role','title','signature']
    
    
    class CourseModelsSerializer(serializers.ModelSerializer):
        # teacher_name = serializers.CharField(source='teacher.name')  #自定义字段,通过sourse关键字就能获取外键关联的指定字段数据,别忘了在fields里面指定一下
        # 方式2
        # 序列化器嵌套
        teacher = TeacherModelSerializer()  #将外键关联的属性指定为关联表的序列化器对象,就能拿到关联表序列化出来的所有数据,还需要在fields中指定一下,注意,名称必须和外键属性名称相同
    
    
        class Meta:
            model = models.Course
            # fields = ["id","name","course_img","students","lessons","pub_lessons","price","teacher",'teacher_name']  #teacher外键属性默认拿的是id值
            fields = ["id","name","course_img","students","lessons","pub_lessons","price","teacher","get_lessons"]  #teacher外键属性默认拿的是id值

    如何通过课程找到课时

    models.py

    class Course(BaseModel):
        
        ......
        class Meta:
            db_table = "ly_course"
            verbose_name = "专题课程"
            verbose_name_plural = "专题课程"
    
        def __str__(self):
            return "%s" % self.name
    
        def lesson_list(self):
            """获取当前课程的前8个课时展示到列表中"""
    
            # 获取所有章节
            chapters_list = self.coursechapters.filter(is_delete=False,is_show=True)
            lesson_list = [] # 课时列表
            if chapters_list: 
                for chapter in chapters_list:
                    lessons = chapter.coursesections.filter(is_delete=False,is_show=True)[:4]
                    if lessons:
                        for lesson in lessons:
                            lesson_list.append({
                                "id":lesson.id,
                                "name":lesson.name,
                                "free_trail":lesson.free_trail
                            })
    
            return lesson_list[:4]

    序列化器字段增加自定义的模型字段

    class CourseModelSerializer(serializers.ModelSerializer):
    # 默认情况,序列化器转换模型数据时,默认会把外键直接转成主键ID值 # 所以我们需要重新设置在序列化器中针对外键的序列化 # 这种操作就是一个序列器里面调用另一个序列化器了.叫"序列化器嵌套"

    teacher = TeacherModelSerializer() # coursechapters = CourseChapterModelSerializer(many=True) class Meta: model = Course fields = ("id","name","course_img","students","lessons","pub_lessons","price","teacher","lesson_list")

    6.前端显示列表课程信息

    <!-- html -->  
    <div class="course-list">
            <div class="course-item" v-for="(course, courseindex) in course_list">
              <div class="course-image">
    
                <img :src="course.course_img" alt="">
    
              </div>
              <div class="course-info">
                <h3><router-link to="">{{course.name}}</router-link> <span><img src="/static/img/avatar1.svg" alt="">{{course.students}}人已加入学习</span></h3>
                <p class="teather-info">{{course.teacher.name}} {{course.teacher.signature}} {{course.teacher.title}} <span>共{{course.lessons}}
                  课时/{{course.lessons===course.pub_lessons? '更新完成':`已更新${course.pub_lessons}课时`}}</span></p>
                <ul class="lesson-list">
                  <li v-for="(lesson, lessonindex) in course.get_lessons" :key="lessonindex"><span class="lesson-title">0{{lessonindex+1}} | 第{{lesson.lesson}}节:{{lesson.name}}</span><span v-show="lesson.free_trail" class="free">免费</span></li>
    
                </ul>
                <div class="pay-box">
                  <span class="discount-type">限时免费</span>
                  <span class="discount-price">¥0.00元</span>
                  <span class="original-price">原价:{{course.price}}元</span>
                  <span class="buy-now">立即购买</span>
                </div>
              </div>
            </div>
    // js
    <script>
      export default {
          name: "Course",
          data(){
            return{
              course_list:[],
            }
          },
          created() {
            this.get_course();
          },
          methods:{
              
            // 获取课程列表数据
            get_course(){
              this.$axios.get(`${this.$settings.Host}/course/courses/`,{
                params:this.fitlers,
              })
              .then((res)=>{
                this.total = res.data.count
                this.course_list = res.data.results;
              })
            }
          }
    
      }
    </script>

    7.按照指定分类显示课程信息

    1.安装字段过滤排序

    pip install django-filter

    2.在settings/dev.py配置文件中增加过滤后端的设置

    INSTALLED_APPS = [
        ...
        'django_filters',  # 需要注册应用,
    ]

    3.在视图中设置允许过滤的字段名和引入过滤字段核心类

    from .serializers import CourseModelSerializer
    from django_filters.rest_framework import DjangoFilterBackend
    class CourseAPIView(ListAPIView):
        queryset = Course.objects.filter(is_delete=False, is_show=True).order_by("orders")
        serializer_class = CourseModelSerializer
        filter_backends = [DjangoFilterBackend, ]
        filter_fields = ('course_category',)

    drf测试接口:course/courses/?course_category=1

    可以看到分类为1的所有课程信息

    4.前端显示

    <script>
      import Vheader from "./common/Vheader"
      import Footer from "./common/Footer"
      export default {
          name: "Course",
          data(){
            return{
              category:0,  //默认分类值为0 全部
              category_list:[],
              course_list:[],
              fitlers:{},
              total:0
            }
          },
          components:{
            Vheader,
            Footer,
          },
    
          created() {
            this.get_categorys();
            this.get_course();
    
          },
          watch:{
    
            category(){
              if (this.category>0){
                this.fitlers['course_category'] = this.category;
              }else {
                this.fitlers={}
              }
    
              //console.log('>>>>>',this.fitlers)
              this.get_course(); // 当分类数据发生变化时,触发获取数据的动作
            }
          },
            // 获取所有分类数据
            get_categorys(){
              this.$axios.get(`${this.$settings.Host}/course/categorys/`)
            .then((res)=>{
              //console.log(res.data);
              this.category_list = res.data;
            })
            },
    
            // 获取课程列表数据
            get_course(){
              this.$axios.get(`${this.$settings.Host}/course/courses/`,{
                params:this.fitlers,
              })
              .then((res)=>{
                //console.log(res.data);
                this.total = res.data.count
                this.course_list = res.data.results;
              })
            }
          }
    
    
      }
    </script>

    8.分页显示课程信息

    1.前端

    <template>
         .....
          <!-- 分页效果展示 -->
          <el-pagination
            background
            :page-size="2"
            layout="prev, pager, next, sizes,jumper"
            :page-sizes="[2, 5,  10, 15, 20]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :total="total">
          </el-pagination>
    
        </div>
        <Footer></Footer>
      </div>
    </template>
    
    <script>
      import Vheader from "./common/Vheader"
      import Footer from "./common/Footer"
      export default {
          name: "Course",
          data(){
           
            }
          },
          components:{
           
          },
    
          created() {
         
          },
              
          },
          methods:{
            handleSizeChange(val){
              this.fitlers['size'] = val
              // console.log(val);
              this.get_course();
            },
            handleCurrentChange(val){
              this.fitlers['page'] = val
              // console.log(val);
              this.get_course();
            },
    
            // 获取所有分类数据
            get_categorys(){
            
            })
            },
    
            // 获取课程列表数据
            get_course(){
                
              })
            }
          }
    
    
      }
    </script>

    2.后端

    pagenation.py

    from rest_framework.pagination import PageNumberPagination
    class StandardPageNumberPagination(PageNumberPagination):
        # 默认每一页显示的数据量
        page_size = 2
        # 允许客户端通过get参数来控制每一页的数据量
        page_size_query_param = "size"
        max_page_size = 10  #客户端通过size指定获取数据的条数时,最大不能超过多少

    views.py

    from django.shortcuts import render
    
    
    from .pagenations import StandardPageNumberPagination
    
    # 加过滤
    class CourseView(ListAPIView):
        ......
        pagination_class = StandardPageNumberPagination 

    drf接口调试

    course/courses/?page=1

    course/courses/?page=1&size=5

  • 相关阅读:
    Quartus II 12.0傻瓜版安装教程(附下载链接)
    MathType 免费版安装教程(附下载链接)
    Matlab与Visual Studio 安装和联合编译配置(附下载链接)
    操作系统的概述
    Sublime Text 3 安装,C/C++代码的编译运行以及代码格式化的配置 (附下载链接)
    DSP中的DELAY_US ( )函数存放在FLASH下执行在RAM中的方法
    vtk:如何利用鼠标交会三维模型,获取交点坐标?
    进一步完善了近景摄影测量和低空数据处理软件!
    SURF算法速度更快!
    vtk:如何使用鼠标选中多个点?
  • 原文地址:https://www.cnblogs.com/libolun/p/13922948.html
Copyright © 2020-2023  润新知