1. Django缓存到redis中
django_redis模块.(继承django的cache, 使用方式进而cache的使用一致, 数据被加密存到redis中)
* 1. pip install django_redis
* 2. 在settings/.py 配置文件中配置django_redis的信息
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"CONNECTION_POOL_KWARGS": {"max_connections": 100}
}
}
}
配置之后, 短信验证码会保存到redis中.
文件夹是自动创建的...
2. 缓存轮播图
修改轮播图接口, 优先从redis中获取用户的数据, 如果redis中不存在, 再去数据库中获取数据. 获取之后保存
一份到redis中.
视图类继承ListAPIView类, 路由匹配成功会自动调用视图类的list方法.
原来接口使用的内置的list方法获取轮播图的数据,
自定义list方法, 先充redis中获取数据, 如果获取到了, 使用自定义的response返回数据.
没有获取到数据,调用父类的list方法, 去数据库中读取数据,
返回response对象, 从response.data中获取数据, 使用自定义的response返回数据.
from rest_framework.generics import ListAPIView
from . import models
from utils import Serializer, api_response
from django.conf import settings
from django.core.cache import cache
class CarouselAPI(ListAPIView):
queryset = models.CarouselModel.objects.filter(is_delete=False, is_show=True).order_by('display_order')[
:settings.CAROUSEL_SHOW_QUANTITY]
serializer_class = Serializer.CarouselModelSerializer
def list(self, request, *args, **kwargs):
carousel_list = cache.get('Carousel_list')
if carousel_list:
return api_response.ResponseDataFormat(data=carousel_list)
print('走数据库!')
res = super().list(request, *args, **kwargs)
cache.set('Carousel_list', res.data, 60 * 60 * 24)
return api_response.ResponseDataFormat(data=res.data)
第一次获取数据redis中肯定没有数据, 去数据库中拿, 之后在数据没有过期的情况下都会去redis中获取.
3. 定时更新录播图缓存
* 1. 安装celery模块
pip install celery==4.4.6
* 2. 安装eventlet( windows 需要下载eventlet 模块 )
pip install eventlet
* 3. 在项目根目录下新建celert_task包.
* 4. 在celery_task在新建celery.py 文件(名称固定).
* 5. 在celery.py中创建定时任务
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'luffy.settings.dev')
django.setup()
from celery import Celery
from datetime import timedelta
broker = 'redis://127.0.0.1:6379/1'
backend = 'redis://127.0.0.1:6379/2'
app = Celery(__name__, broker=broker, backend=backend, include=['celery_task.home_task'])
app.conf.timezone = 'Asia/Shanghai'
app.conf.enable_utc = False
app.conf.beat_schedule = {
'carousel_update': {
'task': 'celery_task.home_task.carousel_update',
'schedule': timedelta(seconds=60 * 60),
}
}
* 6. 启动worker端, hang住等待任务...
PS F:\synchro\Project\luffy>
celery worker -A celery_task -l info -P eventlet
* 7. 在celery_task包目录下新建home_task.py 文件, 首页轮播图任务
from .celery import app
@app.task
def carousel_update():
from home import models
from utils.Serializer import CarouselModelSerializer
from django.conf import settings
queryset = models.CarouselModel.objects.filter(is_delete=False, is_show=True).order_by('display_order')[
:settings.CAROUSEL_SHOW_QUANTITY]
ser = CarouselModelSerializer(instance=queryset, many=True)
print(ser.data)
* 8. 启动beat端
celery beat -A celery_task -l info
添加一次任务后, ctrl + c 终止beat端
* 9. worker端查看结果
[OrderedDict([('name', 'Carouse1'), ('link', 'free-course'), ('img', '/media/Carousel/Carouse1.png')]),
OrderedDict([('name', 'Carouse2'), ('link', 'actual-course'), ('img', '/media/Carousel/Carouse2.png')]),
OrderedDict([('name', 'Carouse3'), ('link', 'light-course'), ('img', '/media/Carousel/Carouse3.png')])]
* 10. 手动拼接路径
在视图类中获取的数据会或request对象中取出地址拼接, 而在这里没有request对象不会自动地址, 需要手动加.
from .celery import app
@app.task
def carousel_update():
from home import models
from utils.Serializer import CarouselModelSerializer
from django.conf import settings
from django.core.cache import cache
queryset = models.CarouselModel.objects.filter(is_delete=False, is_show=True).order_by('display_order')[
:settings.CAROUSEL_SHOW_QUANTITY]
ser = CarouselModelSerializer(instance=queryset, many=True)
print(ser.data)
for dic in ser.data:
dic['img'] = 'https://127.0.0.1:8000' + dic['img']
cache.set('Carousel_list', ser.data)
print(cache.get('Carousel_list'))
return True
* 11. 删除数据
删除一个拖, is_delete=True, 操作之后记得更新到数据库!
* 12. 启动beat端
celery beat -A celery_task -l info
添加一次任务后, ctrl + c 终止beat端
[OrderedDict([('name', 'Carouse2'), ('link', 'actual-course'), ('img', '/media/Carousel/Carouse2.png')]),
OrderedDict([('name', 'Carouse3'), ('link', 'light-course'), ('img', '/media/Carousel/Carouse3.png')])]
[OrderedDict([('name', 'Carouse2'), ('link', 'actual-course'), ('img', 'https://127.0.0.1:8000/media/Carousel/Carouse2.png')]),
OrderedDict([('name', 'Carouse3'), ('link', 'light-course'), ('img', 'https://127.0.0.1:8000/media/Carousel/Carouse3.png')])]
* 13. 删除测试代码, 将删除的照片恢复.
print(ser.data) # 测试成功删除
print(ser.data) # 测试成功删除
3. 免费课程群查接口
3.1 创建课程app
* 1. 创建course app
PS F:\synchro\Project\luffy> cd .\luffy\apps\
PS F:\synchro\Project\luffy\luffy\apps> python ../../manage.py startapp course
* 2. 在settings/dev.py中注册course app
INSTALLED_APPS = [
...
'course',
]
* 3. 配置路由(主路由 urls.py)
urlpatterns = [
...
path('course/', include('course.urls'))
]
* 4. 在course 目录下新建urls.py文件(子路由)
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
3.2 关系字段(补充)
ForeignKey参数: (设置要关联的表的字段)
related_name='xxx' : 反向操作时, 使用的字段名, 用与代替原反向查询时的'表名小写_set'
related_quert_name='xx' : 反向查询操作时, 使用'xx__', 代替 '虚拟字段名__'.
class Classes(models.Model):
name = models.CharField(max_length=32)
class Student(models.Model):
name = models.CharField(max_length=32)
theclass = models.ForeignKey(to='Classes', related_name='students', related_quert_name='x')
要查询某个班级关联的所有学生(反向查询):
models.Classes.objects.first().student_set.all()
models.Classes.objects.values('theclass__name')
在ForeignKey中设置了related_name参数后:
models.Classes.objects.first().students.all()
在ForeignKey中设置了related_quert_name参数后:
models.Classes.objects.values('x__name')
3.3 表设置
1. 基础表
from django.db import models
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False, verbose_name='是否删除')
is_show = models.BooleanField(default=True, verbose_name='是否展示')
created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
updated_time = models.DateTimeField(auto_now=True, verbose_name='最后更新时间')
orders = models.IntegerField(verbose_name='排序')
class Meta:
abstract = True
2. 分类表
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 f'{self.name}'
3. 导师表
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, null=True, blank=True, verbose_name='导师签名', help_text='导师签名')
image = models.ImageField(upload_to='teach', null=True, blank=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 f'{self.name}'
4. 课程表
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, null=True, blank=True, verbose_name='封面图片')
course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name='付费类型')
brief = models.TextField(max_length=2048, null=True, blank=True, verbose_name='详情介绍')
level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name='难度等级')
pub_date = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
period = models.IntegerField(default=7, verbose_name='建议学习周期(day)')
attachment_path = models.FileField(upload_to='attachment', max_length=128,
null=True,
blank=True,
verbose_name='课件路径')
status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name='课程状态')
price = models.DecimalField(max_digits=6, decimal_places=2, defaule=0, verbose_name='课程原价')
students = models.IntegerField(default=0, verbose_name='学习人数')
sections = models.IntegerField(default=0, verbose_name='总课时数量')
pub_sections = models.IntegerField(default=0, verbose_name='课时更新数量')
course_category = models.ForeignKey(to='CourseCategory', on_delete=models.SET_NULL, null=True, blank=True,
db_constraint=False,
verbose_name='课程分类')
teacher = models.ForeignKey(to='Teacher', on_delete=models.DO_NOTHING, null=True, blank=True, db_constraint=False,
verbose_name='授课老师', )
class Meta:
db_table = 'luffy_course'
verbose_name = '课程'
verbose_name_plural = verbose_name
def __str__(self):
return f'{self.name}'
5. 章节表
class CourseChapter(BaseModel):
"""
课程表(一) 对 (多)章节表
"""
chapter = models.SmallIntegerField(default=1, verbose_name="第几章")
name = models.CharField(max_length=128, verbose_name="章节标题")
summary = models.TextField(null=True, blank=True, verbose_name="章节介绍")
pub_date = models.DateField(auto_now_add=True, verbose_name="发布日期")
course = models.ForeignKey(to="Course", related_name='course_chapters', on_delete=models.CASCADE,
db_constraint=False, verbose_name="课程名称")
class Meta:
db_table = "luffy_course_chapter"
verbose_name = "章节"
verbose_name_plural = verbose_name
def __str__(self):
return f'{self.course}: 第{self.chapter}章{self.name}'
6. 课时表
class CourseSection(BaseModel):
"""
章节表 (一) 对 (多) 课时表
"""
section_type_choices = (
(0, '文档'),
(1, '练习'),
(2, '视频')
)
name = models.CharField(max_length=128, verbose_name='课时标题')
orders = models.PositiveIntegerField(verbose_name='课时排序')
section_type = models.SmallIntegerField(choices=section_type_choices, default=2, verbose_name='课时种类')
section_link = models.CharField(max_length=255, null=True, blank=True, verbose_name='课时链接',
help_text='若是video填vid, 若是文档, 填link'
)
duration = models.CharField(max_length=32, null=True, blank=True, verbose_name='视频时长')
pub_data = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
free_trail = models.BooleanField(default=False, verbose_name='是否可以试看')
chapter = models.ForeignKey(to='CourseChapter',
related_name='course_sections',
on_delete=models.CASCADE,
db_constraint=False,
verbose_name='课程章节')
class Meta:
db_table = 'luffy_course_Section'
verbose_name = '课时'
verbose_name_plural = verbose_name
def __str__(self):
return f'{self.chapter} - {self.name}'
7. 数据量迁移
python manage.py makemigrations
python manage.py migrate
8. 注册表到后台
在Course App下的admin.py 中将创建的表注册到后台.
import xadmin
from . import models
xadmin.site.register(models.CourseCategory)
xadmin.site.register(models.Teacher)
xadmin.site.register(models.Course)
xadmin.site.register(models.CourseChapter)
xadmin.site.register(models.CourseSection)
9. 后台菜单改为中文
Django 实现xadmin后台菜单改为中文
* 1. 应用目录下apps.py
from django.apps import AppConfig
class CourseConfig(AppConfig):
name = 'course'
verbose_name = "课程表"
* 2. 应用目录下__init__.py
default_app_config = "course.apps.CourseConfig"
3.4 写入数据
1. 图片资源
在luffy/media/下新建 teacher目录 与 course目录
头像图片放在 media/teacher 文件夹下
课程图片放在 media/course 文件夹下
2. 分类表
使用navicat传数据.
INSERT INTO luffy_course_category(id, orders, is_show, is_delete, created_time, updated_time, name) VALUES (1, 1, 1, 0, '2019-07-14 13:40:58.690413', '2019-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, '2019-07-14 13:41:08.249735', '2019-07-14 13:41:08.249817', 'Linux');
3. 导师表
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, '2019-07-14 13:44:19.661327', '2019-07-14 13:46:54.246271', '无极剑圣·易', 1, '教学总监', '王牌', 'teacher/无极剑圣.png', '无极剑圣·易,是MOBA竞技网游《英雄联盟》中的一位英雄角色,英雄定位为战士、刺客。易大师是一个有超高机动性的刺客、战士型英雄,擅长利用快速的打击迅速击溃对手,易大师一般打野和走单人路,作为无极剑道的最后传人,易可以迅速砍出大量伤害,同时还能利...');
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, '2019-07-14 13:45:25.092902', '2019-07-14 13:45:25.092936', '永恒梦魇', 0, '导师1', '金牌', 'teacher/永恒梦魇.png', '永恒梦魇是英雄联盟当中一个很强力的打野英雄,由于他的被动效果和Q技能导致他的清野效率非常的高。Q技能具有AOE伤害,而被动效果具有溅射伤害,可以快速帮助他刷完石头以及大鸟的...');
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, '2019-07-14 13:46:21.997846', '2019-07-14 13:46:21.997880', '武器大师·贾克斯', 0, '导师2', '银牌', 'teacher/武器大师.png', '武器大师·贾克斯,是MOBA竞技网游《英雄联盟》中的英雄角色。贾克斯是一个万金油型的英雄,他可以适应任何阵容。取得优势的武器可以输出成吨的伤害,而且魔法和物理的混合伤害也让对面..');
4. 课程表
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, '2019-07-14 13:54:33.095201', '2019-07-14 13:54:33.095238', 'Python开发21天入门', 'courses/python1.png', 0, 'Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土&&&Python从入门到入土', 0, '2019-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, '2019-07-14 13:56:05.051103', '2019-07-14 13:56:05.051142', 'Python项目实战', 'courses/python2.png', 0, 'python进阶', 1, '2019-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, '2019-07-14 13:57:21.190053', '2019-07-14 13:57:21.190095', 'Linux系统基础5周入门精讲', 'courses/linux.png', 0, 'linux基础', 0, '2019-07-14', 25, '', 0, 219, 100, 100, 39.00, 2, 3);
5. 章节表
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, '2019-07-14 13:58:34.867005', '2019-07-14 14:00:58.276541', 1, '计算机原理', '', '2019-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, '2019-07-14 13:58:48.051543', '2019-07-14 14:01:22.024206', 2, '环境搭建', '', '2019-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, '2019-07-14 13:59:09.878183', '2019-07-14 14:01:40.048608', 1, '项目创建', '', '2019-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, '2019-07-14 13:59:37.448626', '2019-07-14 14:01:58.709652', 1, 'Linux环境创建', '', '2019-07-14', 3);
6. 课时表
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, '2019-07-14 14:02:33.779098', '2019-07-14 14:02:33.779135', '计算机原理上', 1, 2, NULL, NULL, '2019-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, '2019-07-14 14:02:56.657134', '2019-07-14 14:02:56.657173', '计算机原理下', 2, 2, NULL, NULL, '2019-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, '2019-07-14 14:03:20.493324', '2019-07-14 14:03:52.329394', '环境搭建上', 1, 2, NULL, NULL, '2019-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, '2019-07-14 14:03:36.472742', '2019-07-14 14:03:36.472779', '环境搭建下', 2, 2, NULL, NULL, '2019-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, '2019-07-14 14:04:19.338153', '2019-07-14 14:04:19.338192', 'web项目的创建', 1, 2, NULL, NULL, '2019-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, '2019-07-14 14:04:52.895855', '2019-07-14 14:04:52.895890', 'Linux的环境搭建', 1, 2, NULL, NULL, '2019-07-14 14:04:52.895942', 1, 4);
3.5 分类接口
访问分类表, 获取所有分类的id与名称.
* 后续点击该分类时, 提交分类的id, 通过进行赛选!
* 1. 路由层
from django.urls import re_path, include
from . import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('categories', views.CourseCategoryView, 'categories')
urlpatterns = [
re_path('', include(router.urls)),
]
* 2. 模型序列化器
from rest_framework import serializers
from . import models
class CourseCategoryModelsSerializer(serializers.ModelSerializer):
class Meta:
model = models.CourseCategory
fields = ['id', 'name']
* 3. 视图类
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from . import models
from . import serializer
from utils import api_response
class CourseCategoryView(GenericViewSet, ListModelMixin):
queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseCategoryModelsSerializer
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
* 4. 测试地址: http://127.0.0.1:8000/course/categories/
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pcjc7Zvr-1654244938465)(C:/Users/13600/AppData/Roaming/Typora/typora-user-images/image-20220530233520830.png)]
3.6 课程接口测试
需要展示的字段:
课程id, 课程name, 课程封面图片, 课程详情, 导师, 课程类型名称, 课程状态, 难度等级
四个课时名称
* 1. 路由
router.register('free', views.CourseView, 'free')
* 2. 序列化类 (子序列化方法, 字段是另一个模型表的数据)
class TeacherModelsSerializer(serializers.ModelSerializer):
class Meta:
model = models.Teacher
fields = ['name', 'title', 'role_name']
class CourseModelSerializer(serializers.ModelSerializer):
teacher = TeacherModelsSerializer()
class Meta:
model = models.Course
fields = [
'id',
'name',
'course_img',
'teacher',
'brief',
'course_type_name',
'level_name',
'status_name',
'get_course_chapter'
]
序列化类中使用的字段可以是模型类的中方法.
模型类中的方法使用@property 将方法装饰为属性.
@property
def role_name(self):
return self.get_role_display()
@property
def course_type_name(self):
return self.get_course_type_display()
@property
def level_name(self):
return self.get_level_display()
@property
def status_name(self):
return self.get_status_display()
@property
def get_course_chapter(self):
"""
1. 先获取到所有章节表的对象
课程表查章节表 --> 反向查询 --> self.表名小写_set
self是课程表对象, 章节表中外键绑定课程表设置了 related_name='course_chapters'
course_chapters 替代 表名小写_set
"""
all_chapter_obj = self.course_chapters.all()
"""
2. 遍历章节对象, 章节对象反向查询课时表所有对象, 再遍历课时表获取课时名称(四个即可)
课时表表中外键绑章节表设置了 related_name='course_sections',
"""
chapter_list = []
for chapter_obj in all_chapter_obj:
for course_section_obj in chapter_obj.course_sections.all():
chapter_list.append({
'name': course_section_obj.name,
'link': course_section_obj.section_link
})
if len(chapter_list) == 4:
return chapter_list
return chapter_list
* 3. 分页器
from rest_framework.pagination import PageNumberPagination as DRFPageNumberPagination
class PageNumberPagination(DRFPageNumberPagination):
page_size = 1
page_query_param = 'page'
page_size_query_param = 'page_size'
max_page_size = 10
* 4. 视图类
class CourseView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from .paginations import PageNumberPagination
pagination_class = PageNumberPagination
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
* 5. 测试地址 http://127.0.0.1:8000/course/free/
3.7 排序过滤测试
使用rest_framework内置的排序模块(指定的字段不能是外键!)
* 1. 修改 apps/course/serializer.py 文件, 测试排序, 不展示太多的字段信息
class CourseModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Course
fields = [
'id',
'name',
'price',
]
* 2. 修改视图类, 测试排序不需要使用分页器.
class CourseView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from rest_framework.filters import OrderingFilter, SearchFilter
filter_backends = [OrderingFilter, SearchFilter]
ordering_fields = ['id', 'price']
search_fields = ['id']
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
1. 排序源码分析
1. 视图类继承了GenericViewSet与ListModelMixin
GenericViewSet 继承了 (ViewSetMixin, generics.GenericAPIView)
2. 在路由匹配成功之后会执行list方法.
class ListModelMixin:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
3. queryset = self.filter_queryset(self.get_queryset())
self是当前视图类, self.get_queryset是GenericAPIView提供的, 获取数据对象,
filter_queryset, 也是GenericAPIView提供的.
4. filter_queryset方法中使用视图类的filter_backends属性.
filter_backends属性在单独配置的时候值可以是单独的一个对象OrderingFilter
视图类中
filter_backends = [OrderingFilter] list([OrderingFilter])还是[OrderingFilter]
数图类中使用 filter_backends = [排序类, 过滤类] 遍历这个列表生成一个个的对象.
如果视图类中
filter_backends = OrderingFilter 则 list(OrderingFilter) => [OrderingFilter]
def filter_queryset(self, queryset):
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
5. OrderingFilter对象的filter_queryset方法
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
if ordering:
return queryset.order_by(*ordering)
return queryset
6. OrderingFilter对象的get_ordering方法
def get_ordering(self, request, queryset, view):
"""
获取路由地址?ordering=xx的值,
self.ordering_param
ordering_param = api_settings.ORDERING_PARAM 从配置文件中获取 'ORDERING_PARAM': 'ordering'
支持 ordering=id, xx (多值) 结果是一个字符串 'id, xx'
"""
params = request.query_params.get(self.ordering_param)
if params:
"""
params.split(',') 字符串按,切分得到一个列表['id', 'xx']
从列表中取出一个个值, ''.strip() 取出移除字符串头尾指定的字符(默认为空格)
"""
fields = [param.strip() for param in params.split(',')]
ordering = self.remove_invalid_fields(queryset, fields, view, request)
if ordering:
return ordering
return self.get_default_ordering(view)
* 7. 排序测试
按价格排序(正序): http://127.0.0.1:8000/course/free/?ordering=price
按价格排序(倒序): http://127.0.0.1:8000/course/free/?ordering=-price
2. 过滤源码分析
1. 执行过滤对象的filter_queryset方法
def filter_queryset(self, queryset):
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
* 2. SearchFilter过滤对象filter_queryset的方法源码
def get_search_fields(self, view, request):
return getattr(view, 'search_fields', None)
def get_search_terms(self, request):
"""
self.search_param
search_param => api_settings.SEARCH_PARAM => 'SEARCH_PARAM': 'search',
获取?search=''的值, 值是一个字段串, 值可以有多个使用, 空格分隔
"""
params = request.query_params.get(self.search_param, '')
params = params.replace('\x00', '')
params = params.replace(',', ' ')
return params.split()
lookup_prefixes = {
'^': 'istartswith',
'=': 'iexact',
'@': 'search',
'$': 'iregex',
}
def construct_search(self, field_name):
lookup = self.lookup_prefixes.get(field_name[0])
if lookup:
field_name = field_name[1:]
else:
lookup = 'icontains'
return LOOKUP_SEP.join([field_name, lookup])
def filter_queryset(self, request, queryset, view):
search_fields = self.get_search_fields(view, request)
search_terms = self.get_search_terms(request)
if not search_fields or not search_terms:
return queryset
orm_lookups = [
self.construct_search(str(search_field))
for search_field in search_fields
]
base = queryset
conditions = []
for search_term in search_terms:
queries = [
models.Q(**{orm_lookup: search_term})
for orm_lookup in orm_lookups
]
conditions.append(reduce(operator.or_, queries))
queryset = queryset.filter(reduce(operator.and_, conditions))
if self.must_call_distinct(queryset, search_fields):
queryset = distinct(queryset, base)
return queryset
* 3. 测试地址 http://127.0.0.1:8000/course/free/?search=2
过滤条件id=2, search==id
3. django-filter过滤方式1
rest_framework 的SearchFilter类只支持过滤模型表基本字段, 不支持外键字段.
django-filter模块支持以外键字段过滤.
# 导入django-filters
from django_filters.rest_framework import DjangoFilterBackend
# 视图类中指定django-filters的过滤字段
filter_fields = ['course_category']
# 使用: 赛选字段使用字段名称 ?course_category=值
* 1. 安装django-filter模块
命令: pip install django-filter
* 2. 使用django-filter模块
class CourseView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [DjangoFilterBackend]
filter_fields = ['course_category']
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
* 3. 测试地址: http://127.0.0.1:8000/course/free/?course_category=1
course_category=1, course_category外键1对应这课程为Python的课程
4. django-filter过滤方式2
* 1. 在apps/scourse下新建filter_test.py 文件
from django_filters.filterset import FilterSet
from . import models
class CourseFilterSet(FilterSet):
class Meta:
model = models.Course
fields = ['course_category']
* 2. 视图类中使用
class CourseView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [DjangoFilterBackend]
from .filter_test import CourseFilterSet
filter_class = CourseFilterSet
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
* 3. 测试地址: http://127.0.0.1:8000/course/free/?course_category=1
5.django-filter区间过滤
* 1. 修改CourseFilterSet类
from django_filters.filterset import FilterSet
from . import models
from django_filters import filters
class CourseFilterSet(FilterSet):
min_price = filters.NumberFilter(field_name='price', lookup_expr='gt')
max_price = filters.NumberFilter(field_name='price', lookup_expr='lt')
class Meta:
model = models.Course
fields = ['course_category']
* 2. 测试地址: http://127.0.0.1:8000/course/free/?max_price=100&min_price=-1
min_price=0 的意思是 大于0的意思 如果 ?max_price=100&min_price=-1 则id为1的数据不会显示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IUMQFnRF-1654244938469)(C:/Users/13600/AppData/Roaming/Typora/typora-user-images/image-20220601232545399.png)]
* 3. 如果提示没有模块, 则在配置文件中注册django_filters
INSTALLED_APPS = [
...
'django_filters',
]
6.django-filter源码分析
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [DjangoFilterBackend]
filter_fields = ['course']
filter_class = CourseFilterSet
从执行 GenericAPIView的filter_queryset方法开始
def filter_queryset(self, queryset):
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
def filter_queryset(self, request, queryset, view):
filterset = self.get_filterset(request, queryset, view)
if filterset is None:
return queryset
if not filterset.is_valid() and self.raise_exception:
raise utils.translate_validation(filterset.errors)
return filterset.qs
class BaseFilterSet:
...
@property
def qs(self):
if not hasattr(self, '_qs'):
qs = self.queryset.all()
if self.is_bound:
self.errors
qs = self.filter_queryset(qs)
self._qs = qs
return self._qs
def get_filterset(self, request, queryset, view):
filterset_class = self.get_filterset_class(view, queryset)
if filterset_class is None:
return None
kwargs = self.get_filterset_kwargs(request, queryset, view)
return filterset_class(**kwargs)
def get_filterset_kwargs(self, request, queryset, view):
return {
'data': request.query_params,
'queryset': queryset,
'request': request,
}
def get_filterset_class(self, view, queryset=None):
filterset_class = getattr(view, 'filterset_class', None)
filterset_fields = getattr(view, 'filterset_fields', None)
if filterset_class is None and hasattr(view, 'filter_class'):
utils.deprecate(
"`%s.filter_class` attribute should be renamed `filterset_class`."
% view.__class__.__name__)
filterset_class = getattr(view, 'filter_class', None)
if filterset_fields is None and hasattr(view, 'filter_fields'):
utils.deprecate(
"`%s.filter_fields` attribute should be renamed `filterset_fields`."
% view.__class__.__name__)
filterset_fields = getattr(view, 'filter_fields', None)
if filterset_class:
filterset_model = filterset_class._meta.model
if filterset_model and queryset is not None:
assert issubclass(queryset.model, filterset_model), \
'FilterSet model %s does not match queryset model %s' % \
(filterset_model, queryset.model)
return filterset_class
if filterset_fields and queryset is not None:
MetaBase = getattr(self.filterset_base, 'Meta', object)
class AutoFilterSet(self.filterset_base):
class Meta(MetaBase):
model = queryset.model
fields = filterset_fields
return AutoFilterSet
return None
class DjangoFilterBackend(metaclass=RenameAttributes):
filterset_base = filterset.FilterSet
...
class FilterSet(filterset.FilterSet):
...
class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass):
pass
class BaseFilterSet:
...
7. 总结
排序:
类配置属性: filter_backends=[OrderingFilter]
配置排序的字段: ordering_fields=['排序的字段1', '排序的字段2']
排序的使用: (按id 正序 倒序)
http://127.0.0.1:8000/course/free/?ordering=排序的字段
过滤:
类配置属性: filter_backends=[SearchFilter]
配置过滤的字段: search_fields = ['过滤的字段1', '过滤的字段2']
过滤的使用:
http://127.0.0.1:8000/course/free/?search=过滤的字段
django-filter: (过滤方式1)
类配置属性: filter_backends=[DjangoFilterBackend]
配置过滤的字段: filter_fields = ['过滤的字段1', '过滤的字段2']
过滤的使用:
http://127.0.0.1:8000/course/free/?过滤的字段=过滤的值
django-filter: (过滤方式2)
类配置属性: filter_backends=[DjangoFilterBackend]
配置过滤类: filter_class = CourseFilterSet
过滤的使用:
http://127.0.0.1:8000/course/free/?过滤的字段=过滤的值
django-filter: (区间查询)
类配置属性: filter_backends=[DjangoFilterBackend]
配置过滤类: filter_class = CourseFilterSet
定义过滤类:
...
min_price = filters.NumberFilter(field_name='price', lookup_expr='gt')
max_price = filters.NumberFilter(field_name='price', lookup_expr='lt')
区间的使用:
http://127.0.0.1:8000/course/free/?max=xx&&min=xxx
8. 自定义过滤规则
OrderingFilter 与 SearchFilter都继承了BaseFilterBackend类.
自定义过滤规则类:
1. 需要继承BaseFilterBackend类.
2. 重写filter_queryset方法返回response对象.
* 1. 在apps/scourse/filter_test.py 文件下写自定义过滤规则
获取课程价格大于60块的课程.
from rest_framework.filters import BaseFilterBackend
class MyFilter(BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
price = request.query_params.get('price')
queryset_obj = queryset.filter(price__gt=price)
return queryset_obj
* 2. 使用自定义过滤类
class CourseView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from .filter_test import MyFilter
filter_backends = [MyFilter]
search_fields = ['price']
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
* 3. 测试地址: http://127.0.0.1:8000/course/free/?price=60
3.8 课程&排序&过滤接口
需要展示的字段:
id (课程id) , name (课程名称), course_img (课程封面图片),
brief (课程详情), attachment_path (课件路径), pub_sections (课时更新数量)
price (课程价格), students (学习热度), period (建议学习周期), sections (总课时的数量)
course_type_name (课程类型名称), level_name (等级名称), status_name(状态名称)
teacher 导师表信息( name 导师名字, role_name 角色的值, title 职位, signature 导师签名,
image 导师封面, brief 导师描述),
section_list (name 课时标题, section_link 课时链接, duration 视频时长, free_trail 是否可以试看)
排序的字段: id (课程id), price (课程价格), students (学习热度)
过滤的字段: course_category
* 1. course app的路由
from django.urls import re_path, include
from . import views
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('categories', views.CourseCategoryView, 'categories')
urlpatterns = [
re_path('', include(router.urls)),
]
* 2. 模型层
导师表与课程表添加了几个获取数据的方法.
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, null=True, blank=True, verbose_name='导师签名', help_text='导师签名')
image = models.ImageField(upload_to='teach', null=True, blank=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 f'{self.name}'
@property
def role_name(self):
return self.get_role_display()
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, null=True, blank=True, verbose_name='封面图片')
course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name='付费类型')
brief = models.TextField(max_length=2048, null=True, blank=True, verbose_name='详情介绍')
level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name='难度等级')
pub_date = models.DateTimeField(auto_now_add=True, verbose_name='发布时间')
period = models.IntegerField(default=7, verbose_name='建议学习周期(day)')
attachment_path = models.FileField(upload_to='attachment', max_length=128,
null=True,
blank=True,
verbose_name='课件路径')
status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name='课程状态')
price = models.DecimalField(max_digits=6, decimal_places=2, default=0, verbose_name='课程原价')
students = models.IntegerField(default=0, verbose_name='学习人数')
sections = models.IntegerField(default=0, verbose_name='总课时数量')
pub_sections = models.IntegerField(default=0, verbose_name='课时更新数量')
course_category = models.ForeignKey(to='CourseCategory', on_delete=models.SET_NULL, null=True, blank=True,
db_constraint=False,
verbose_name='课程分类')
teacher = models.ForeignKey(to='Teacher', on_delete=models.DO_NOTHING, null=True, blank=True, db_constraint=False,
verbose_name='授课老师', )
class Meta:
db_table = 'luffy_course'
verbose_name = '课程'
verbose_name_plural = verbose_name
def __str__(self):
return f'{self.name}'
@property
def course_type_name(self):
return self.get_course_type_display()
@property
def level_name(self):
return self.get_level_display()
@property
def status_name(self):
return self.get_status_display()
@property
def section_list(self):
"""
1. 先获取到所有章节表的对象
课程表查章节表 --> 反向查询 --> self.表名小写_set
self是课程表对象, 章节表中外键绑定课程表设置了 related_name='course_chapters'
course_chapters 替代 表名小写_set
"""
all_chapter_obj = self.course_chapters.all()
"""
2. 遍历章节对象, 章节对象反向查询课时表所有对象, 再遍历课时表获取课时名称(四个即可)
课时表表中外键绑章节表设置了 related_name='course_sections',
"""
chapter_list = []
for chapter_obj in all_chapter_obj:
for course_section_obj in chapter_obj.course_sections.all():
chapter_list.append({
'name': course_section_obj.name,
'section_link': course_section_obj.section_link,
'duration': course_section_obj.duration,
'free_trail': course_section_obj.free_trail,
})
if len(chapter_list) == 4:
return chapter_list
return chapter_list
* 3. 模型序列化器
class TeacherModelsSerializer(serializers.ModelSerializer):
class Meta:
model = models.Teacher
fields = ['name', 'title', 'role_name', 'signature', 'image', 'brief']
class CourseModelSerializer(serializers.ModelSerializer):
teacher = TeacherModelsSerializer()
class Meta:
model = models.Course
fields = [
'id',
'name',
'course_img',
'brief',
'attachment_path',
'pub_sections',
'price',
'students',
'period',
'sections',
'course_type_name',
'level_name',
'status_name',
'teacher',
'section_list',
]
* 4. 视图类
class CourseView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from .paginations import PageNumberPagination
pagination_class = PageNumberPagination
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [OrderingFilter, DjangoFilterBackend]
ordering_fields = ['id', 'price', 'students']
filter_fields = ['course_category']
def list(self, request, *args, **kwargs):
res = super().list(self, request, *args, **kwargs)
return api_response.ResponseDataFormat(data=res.data)
* 5. 测试地址: http://127.0.0.1:8000/course/free/
http://127.0.0.1:8000/course/free/?course_category=1 过滤测试(筛选python的课程)
http://127.0.0.1:8000/course/free/?course_category=1&ordering=-id 筛选python的课程反向展示
4. 免费课程前端
如果后台不分页, 数据在response.data中. 如果后台分页, 数据在response.data.results中.
从data的count是数据总数量.
重写了list方法, 使用自定义的response返回数据.
获取数据:
this.course_list = response.data.data.results;
获取数据数量:
this.course_total = response.data.data.count;
<template>
<div class="course">
<Header></Header>
<div class="main">
<div class="condition">
<ul class="cate-list">
<li class="title">课程分类:</li>
<li :class="filter.course_category==0?'this':''" @click="filter.course_category=0">全部</li>
<li :class="filter.course_category==category.id?'this':''" v-for="category in category_list"
@click="filter.course_category=category.id" :key="category.name">{{ category.name }}
</li>
</ul>
<div class="ordering">
<ul>
<li class="title">筛 选:</li>
<li class="default" :class="(filter.ordering=='id' || filter.ordering=='-id')?'this':''"
@click="filter.ordering='-id'">默认
</li>
<li class="hot" :class="(filter.ordering=='students' || filter.ordering=='-students')?'this':''"
@click="filter.ordering=(filter.ordering=='-students'?'students':'-students')">人气
</li>
<li class="price"
:class="filter.ordering=='price'?'price_up this':(filter.ordering=='-price'?'price_down this':'')"
@click="filter.ordering=(filter.ordering=='-price'?'price':'-price')">价格
</li>
</ul>
<p class="condition-result">共{{ course_total }}个课程</p>
</div>
</div>
<div class="course-list">
<div class="course-item" v-for="course in course_list" :key="course.name">
<div class="course-image">
<img :src="course.course_img" alt="">
</div>
<div class="course-info">
<h3>
<router-link :to="'/free/detail/'+course.id">{{ course.name }}</router-link>
<span><img src="@/assets/img/avatar1.svg" alt="">{{ course.students }}人已加入学习</span>
</h3>
<p class="teacher-info">
{{ course.teacher.name }} {{ course.teacher.title }} {{ course.teacher.signature }}
<span v-if="course.sections>course.pub_sections">共{{ course.sections }}课时/已更新{{
course.pub_sections
}}课时</span>
<span v-else>共{{ course.sections }}课时/更新完成</span></p>
<ul class="section-list">
<li v-for="(section, key) in course.section_list" :key="section.name">
<span class="section-title">0{{ key + 1 }} | {{ section.name }}</span>
<span class="free" v-if="section.free_trail">免费</span></li>
</ul>
<div class="pay-box">
<div v-if="course.discount_type">
<span class="discount-type">{{ course.discount_type }}</span>
<span class="discount-price">¥{{ course.real_price }}元</span>
<span class="original-price">原价:{{ course.price }}元</span>
</div>
<span v-else class="discount-price">¥{{ course.price }}元</span>
<span class="buy-now">立即购买</span>
</div>
</div>
</div>
</div>
<div class="course_pagination block">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="filter.page"
:page-sizes="[2, 3, 5, 10]"
:page-size="filter.page_size"
layout="sizes, prev, pager, next"
:total="course_total">
</el-pagination>
</div>
</div>
<Footer></Footer>
</div>
</template>
<script>
import Header from "@/components/Head"
import Footer from "@/components/Footer"
export default {
name: "Course",
data() {
return {
category_list: [],
course_list: [],
course_total: 0,
filter: {
course_category: 0,
ordering: "-id",
page_size: 2,
page: 1,
}
}
},
created() {
this.get_category();
this.get_course();
},
components: {
Header,
Footer,
},
watch: {
"filter.course_category": function () {
this.filter.page = 1;
this.get_course();
},
"filter.ordering": function () {
this.get_course();
},
"filter.page_size": function () {
this.get_course();
},
"filter.page": function () {
this.get_course();
}
},
methods: {
handleSizeChange(val) {
this.filter.page = 1;
this.filter.page_size = val;
},
handleCurrentChange(val) {
this.filter.page = val;
},
get_category() {
this.$axios.get(`${this.$settings.base_url}/course/categories/`).then(response => {
this.category_list = response.data.data;
}).catch(() => {
this.$message({
message: "获取课程分类信息有误,请联系客服工作人员",
})
})
},
get_course() {
let filters = {
ordering: this.filter.ordering,
};
if (this.filter.course_category > 0) {
filters.course_category = this.filter.course_category;
}
if (this.filter.page_size > 0) {
filters.page_size = this.filter.page_size;
} else {
filters.page_size = 5;
}
if (this.filter.page > 1) {
filters.page = this.filter.page;
} else {
filters.page = 1;
}
this.$axios.get(`${this.$settings.base_url}/course/free/`, {
params: filters
}).then(response => {
this.course_list = response.data.data.results;
this.course_total = response.data.data.count;
console.log(this.course_list);
}).catch(() => {
this.$message({
message: "获取课程信息有误,请联系客服工作人员"
})
})
}
}
}
</script>
<style scoped>
.course {
background: #f6f6f6;
}
.course .main {
width: 1100px;
margin: 35px auto 0;
}
.course .condition {
margin-bottom: 35px;
padding: 25px 30px 25px 20px;
background: #fff;
border-radius: 4px;
box-shadow: 0 2px 4px 0 #f0f0f0;
}
.course .cate-list {
border-bottom: 1px solid #333;
border-bottom-color: rgba(51, 51, 51, .05);
padding-bottom: 18px;
margin-bottom: 17px;
}
.course .cate-list::after {
content: "";
display: block;
clear: both;
}
.course .cate-list li {
float: left;
font-size: 16px;
padding: 6px 15px;
line-height: 16px;
margin-left: 14px;
position: relative;
transition: all .3s ease;
cursor: pointer;
color: #4a4a4a;
border: 1px solid transparent;
}
.course .cate-list .title {
color: #888;
margin-left: 0;
letter-spacing: .36px;
padding: 0;
line-height: 28px;
}
.course .cate-list .this {
color: #ffc210;
border: 1px solid #ffc210 !important;
border-radius: 30px;
}
.course .ordering::after {
content: "";
display: block;
clear: both;
}
.course .ordering ul {
float: left;
}
.course .ordering ul::after {
content: "";
display: block;
clear: both;
}
.course .ordering .condition-result {
float: right;
font-size: 14px;
color: #9b9b9b;
line-height: 28px;
}
.course .ordering ul li {
float: left;
padding: 6px 15px;
line-height: 16px;
margin-left: 14px;
position: relative;
transition: all .3s ease;
cursor: pointer;
color: #4a4a4a;
}
.course .ordering .title {
font-size: 16px;
color: #888;
letter-spacing: .36px;
margin-left: 0;
padding: 0;
line-height: 28px;
}
.course .ordering .this {
color: #ffc210;
}
.course .ordering .price {
position: relative;
}
.course .ordering .price::before,
.course .ordering .price::after {
cursor: pointer;
content: "";
display: block;
width: 0;
height: 0;
border: 5px solid transparent;
position: absolute;
right: 0;
}
.course .ordering .price::before {
border-bottom: 5px solid #aaa;
margin-bottom: 2px;
top: 2px;
}
.course .ordering .price::after {
border-top: 5px solid #aaa;
bottom: 2px;
}
.course .ordering .price_up::before {
border-bottom-color: #ffc210;
}
.course .ordering .price_down::after {
border-top-color: #ffc210;
}
.course .course-item:hover {
box-shadow: 4px 6px 16px rgba(0, 0, 0, .5);
}
.course .course-item {
width: 1100px;
background: #fff;
padding: 20px 30px 20px 20px;
margin-bottom: 35px;
border-radius: 2px;
cursor: pointer;
box-shadow: 2px 3px 16px rgba(0, 0, 0, .1);
transition: all .2s ease;
}
.course .course-item::after {
content: "";
display: block;
clear: both;
}
.course .course-item .course-image {
float: left;
width: 423px;
height: 210px;
margin-right: 30px;
}
.course .course-item .course-image img {
max-width: 100%;
max-height: 210px;
}
.course .course-item .course-info {
float: left;
width: 596px;
}
.course-item .course-info h3 a {
font-size: 26px;
color: #333;
font-weight: normal;
margin-bottom: 8px;
}
.course-item .course-info h3 span {
font-size: 14px;
color: #9b9b9b;
float: right;
margin-top: 14px;
}
.course-item .course-info h3 span img {
width: 11px;
height: auto;
margin-right: 7px;
}
.course-item .course-info .teacher-info {
font-size: 14px;
color: #9b9b9b;
margin-top: 1px;
margin-bottom: 14px;
padding-bottom: 14px;
border-bottom: 1px solid #333;
border-bottom-color: rgba(51, 51, 51, .05);
}
.course-item .course-info .teacher-info span {
float: right;
}
.course-item .section-list::after {
content: "";
display: block;
clear: both;
}
.course-item .section-list li {
float: left;
width: 44%;
font-size: 14px;
color: #666;
padding-left: 22px;
background: url("/src/assets/img/play-icon-gray.svg") no-repeat left 4px;
margin-bottom: 15px;
}
.course-item .section-list li .section-title {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
display: inline-block;
max-width: 200px;
}
.course-item .section-list li:hover {
background-image: url("/src/assets/img/play-icon-yellow.svg");
color: #ffc210;
}
.course-item .section-list li .free {
width: 34px;
height: 20px;
color: #fd7b4d;
vertical-align: super;
margin-left: 10px;
border: 1px solid #fd7b4d;
border-radius: 2px;
text-align: center;
font-size: 13px;
white-space: nowrap;
}
.course-item .section-list li:hover .free {
color: #ffc210;
border-color: #ffc210;
}
.course-item {
position: relative;
}
.course-item .pay-box {
position: absolute;
bottom: 20px;
width: 600px;
}
.course-item .pay-box::after {
content: "";
display: block;
clear: both;
}
.course-item .pay-box .discount-type {
padding: 6px 10px;
font-size: 16px;
color: #fff;
text-align: center;
margin-right: 8px;
background: #fa6240;
border: 1px solid #fa6240;
border-radius: 10px 0 10px 0;
float: left;
}
.course-item .pay-box .discount-price {
font-size: 24px;
color: #fa6240;
float: left;
}
.course-item .pay-box .original-price {
text-decoration: line-through;
font-size: 14px;
color: #9b9b9b;
margin-left: 10px;
float: left;
margin-top: 10px;
}
.course-item .pay-box .buy-now {
width: 120px;
height: 38px;
background: transparent;
color: #fa6240;
font-size: 16px;
border: 1px solid #fd7b4d;
border-radius: 3px;
transition: all .2s ease-in-out;
float: right;
text-align: center;
line-height: 38px;
position: absolute;
right: 0;
bottom: 5px;
}
.course-item .pay-box .buy-now:hover {
color: #fff;
background: #ffc210;
border: 1px solid #ffc210;
}
.course .course_pagination {
margin-bottom: 60px;
text-align: center;
}
</style>
5. 课程详情单查接口
在群查接口上添加RetrieveModelMixin视图子类即可.
from rest_framework.mixins import RetrieveModelMixin
class CourseView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
...
测试地址: http://127.0.0.1:8000/course/free/1
6. 课程的课时接口
过滤出某个课程的所有课时.
* 1. 路由
router.register('chapters', views.CourseSectionsView, 'chapters')
* 2. 模型序列化类
class CourseSectionModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.CourseSection
fields = ['name', 'orders', 'duration', 'free_trail', 'section_link', 'section_type_name']
class CourseChapterModelSerializer(serializers.ModelSerializer):
course_sections = CourseSectionModelSerializer(many=True)
class Meta:
model = models.CourseChapter
fields = ['name', 'summary', 'chapter', 'course_sections']
* 3. 视图类
class CourseSectionsView(GenericViewSet, ListModelMixin):
queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseChapterModelSerializer
from django_filters.rest_framework import DjangoFilterBackend
filter_backends = [DjangoFilterBackend]
filter_fields = ['course']
* 4. 测试地址: http://127.0.0.1:8000/course/chapters/?course=pk值
http://127.0.0.1:8000/course/chapters/?course=1
7. 课程详情前台
* 1. 新建页面组件
在src/views/下新建FreeCourseDetail.vue文件
<template>
<div class="detail">
<Header/>
<div class="main">
<div class="course-info">
<div class="wrap-left">
<videoPlayer class="video-player vjs-custom-skin"
ref="videoPlayer"
:playsinline="true"
:options="playerOptions"
@play="onPlayerPlay($event)"
@pause="onPlayerPause($event)">
</videoPlayer>
</div>
<div class="wrap-right">
<h3 class="course-name">{{ course_info.name }}</h3>
<p class="data">
{{ course_info.students }}人在学 课程总时长:{{
course_info.sections
}}课时/{{ course_info.pub_sections }}小时 难度:{{ course_info.level_name }}</p>
<div class="sale-time">
<p class="sale-type">价格 <span class="original_price">¥{{ course_info.price }}</span></p>
<p class="expire"></p>
</div>
<div class="buy">
<div class="buy-btn">
<button class="buy-now">立即购买</button>
<button class="free">免费试学</button>
</div>
</div>
</div>
</div>
<div class="course-tab">
<ul class="tab-list">
<li :class="tabIndex==1?'active':''" @click="tabIndex=1">详情介绍</li>
<li :class="tabIndex==2?'active':''" @click="tabIndex=2">课程章节 <span :class="tabIndex!=2?'free':''">(试学)</span>
</li>
<li :class="tabIndex==3?'active':''" @click="tabIndex=3">用户评论</li>
<li :class="tabIndex==4?'active':''" @click="tabIndex=4">常见问题</li>
</ul>
</div>
<div class="course-content">
<div class="course-tab-list">
<div class="tab-item" v-if="tabIndex==1">
<div class="course-brief" v-html="course_info.brief_text"></div>
</div>
<div class="tab-item" v-if="tabIndex==2">
<div class="tab-item-title">
<p class="chapter">课程章节</p>
<p class="chapter-length">共{{ course_chapters.length }}章 {{ course_info.sections }}个课时</p>
</div>
<div class="chapter-item" v-for="chapter in course_chapters" :key="chapter.name">
<p class="chapter-title"><img src="@/assets/img/enum.svg"
alt="">第{{ chapter.chapter }}章·{{ chapter.name }}
</p>
<ul class="section-list">
<li class="section-item" v-for="section in chapter.coursesections" :key="section.name">
<p class="name"><span class="index">{{ chapter.chapter }}-{{ section.orders }}</span>
{{ section.name }}<span class="free" v-if="section.free_trail">免费</span></p>
<p class="time">{{ section.duration }} <img src="@/assets/img/chapter-player.svg"></p>
<button class="try" v-if="section.free_trail">立即试学</button>
<button class="try" v-else>立即购买</button>
</li>
</ul>
</div>
</div>
<div class="tab-item" v-if="tabIndex==3">
用户评论
</div>
<div class="tab-item" v-if="tabIndex==4">
常见问题
</div>
</div>
<div class="course-side">
<div class="teacher-info">
<h4 class="side-title"><span>授课老师</span></h4>
<div class="teacher-content">
<div class="cont1">
<img :src="course_info.teacher.image">
<div class="name">
<p class="teacher-name">{{ course_info.teacher.name }}
{{ course_info.teacher.title }}</p>
<p class="teacher-title">{{ course_info.teacher.signature }}</p>
</div>
</div>
<p class="narrative">{{ course_info.teacher.brief }}</p>
</div>
</div>
</div>
</div>
</div>
<Footer/>
</div>
</template>
<script>
import Header from "@/components/Head"
import Footer from "@/components/Footer"
import {videoPlayer} from 'vue-video-player';
export default {
name: "FreeCourseDetail",
data() {
return {
tabIndex: 2,
course_id: 0,
course_info: {
teacher: {},
},
course_chapters: [],
playerOptions: {
aspectRatio: '16:9',
sources: [{
type: "video/mp4",
src: ""
}],
}
}
},
created() {
this.get_course_id();
this.get_course_data();
this.get_chapter();
},
methods: {
onPlayerPlay() {
console.log('视频开始播放')
},
onPlayerPause() {
console.log('视频暂停,可以打开广告了')
},
get_course_id() {
this.course_id = this.$route.params.pk || this.$route.query.pk;
if (this.course_id < 1) {
let _this = this;
_this.$alert("对不起,当前视频不存在!", "警告", {
callback() {
_this.$router.go(-1);
}
});
}
},
get_course_data() {
this.$axios.get(`${this.$settings.base_url}/course/free/${this.course_id}/`).then(response => {
this.course_info = response.data;
console.log(this.course_info)
}).catch(() => {
this.$message({
message: "对不起,访问页面出错!请联系客服工作人员!"
});
})
},
get_chapter() {
this.$axios.get(`${this.$settings.base_url}/course/chapters/`, {
params: {
"course": this.course_id,
}
}).then(response => {
this.course_chapters = response.data;
}).catch(error => {
window.console.log(error.response);
})
},
},
components: {
Header,
Footer,
videoPlayer,
}
}
</script>
<style scoped>
.main {
background: #fff;
padding-top: 30px;
}
.course-info {
width: 1200px;
margin: 0 auto;
overflow: hidden;
}
.wrap-left {
float: left;
width: 690px;
height: 388px;
background-color: #000;
}
.wrap-right {
float: left;
position: relative;
height: 388px;
}
.course-name {
font-size: 20px;
color: #333;
padding: 10px 23px;
letter-spacing: .45px;
}
.data {
padding-left: 23px;
padding-right: 23px;
padding-bottom: 16px;
font-size: 14px;
color: #9b9b9b;
}
.sale-time {
width: 464px;
background: #fa6240;
font-size: 14px;
color: #4a4a4a;
padding: 10px 23px;
overflow: hidden;
}
.sale-type {
font-size: 16px;
color: #fff;
letter-spacing: .36px;
float: left;
}
.sale-time .expire {
font-size: 14px;
color: #fff;
float: right;
}
.sale-time .expire .second {
width: 24px;
display: inline-block;
background: #fafafa;
color: #5e5e5e;
padding: 6px 0;
text-align: center;
}
.course-price {
background: #fff;
font-size: 14px;
color: #4a4a4a;
padding: 5px 23px;
}
.discount {
font-size: 26px;
color: #fa6240;
margin-left: 10px;
display: inline-block;
margin-bottom: -5px;
}
.original {
font-size: 14px;
color: #9b9b9b;
margin-left: 10px;
text-decoration: line-through;
}
.buy {
width: 464px;
padding: 0px 23px;
position: absolute;
left: 0;
bottom: 20px;
overflow: hidden;
}
.buy .buy-btn {
float: left;
}
.buy .buy-now {
width: 125px;
height: 40px;
border: 0;
background: #ffc210;
border-radius: 4px;
color: #fff;
cursor: pointer;
margin-right: 15px;
outline: none;
}
.buy .free {
width: 125px;
height: 40px;
border-radius: 4px;
cursor: pointer;
margin-right: 15px;
background: #fff;
color: #ffc210;
border: 1px solid #ffc210;
}
.add-cart {
float: right;
font-size: 14px;
color: #ffc210;
text-align: center;
cursor: pointer;
margin-top: 10px;
}
.add-cart img {
width: 20px;
height: 18px;
margin-right: 7px;
vertical-align: middle;
}
.course-tab {
width: 100%;
background: #fff;
margin-bottom: 30px;
box-shadow: 0 2px 4px 0 #f0f0f0;
}
.course-tab .tab-list {
width: 1200px;
margin: auto;
color: #4a4a4a;
overflow: hidden;
}
.tab-list li {
float: left;
margin-right: 15px;
padding: 26px 20px 16px;
font-size: 17px;
cursor: pointer;
}
.tab-list .active {
color: #ffc210;
border-bottom: 2px solid #ffc210;
}
.tab-list .free {
color: #fb7c55;
}
.course-content {
width: 1200px;
margin: 0 auto;
background: #FAFAFA;
overflow: hidden;
padding-bottom: 40px;
}
.course-tab-list {
width: 880px;
height: auto;
padding: 20px;
background: #fff;
float: left;
box-sizing: border-box;
overflow: hidden;
position: relative;
box-shadow: 0 2px 4px 0 #f0f0f0;
}
.tab-item {
width: 880px;
background: #fff;
padding-bottom: 20px;
box-shadow: 0 2px 4px 0 #f0f0f0;
}
.tab-item-title {
justify-content: space-between;
padding: 25px 20px 11px;
border-radius: 4px;
margin-bottom: 20px;
border-bottom: 1px solid #333;
border-bottom-color: rgba(51, 51, 51, .05);
overflow: hidden;
}
.chapter {
font-size: 17px;
color: #4a4a4a;
float: left;
}
.chapter-length {
float: right;
font-size: 14px;
color: #9b9b9b;
letter-spacing: .19px;
}
.chapter-title {
font-size: 16px;
color: #4a4a4a;
letter-spacing: .26px;
padding: 12px;
background: #eee;
border-radius: 2px;
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
}
.chapter-title img {
width: 18px;
height: 18px;
margin-right: 7px;
vertical-align: middle;
}
.section-list {
padding: 0 20px;
}
.section-list .section-item {
padding: 15px 20px 15px 36px;
cursor: pointer;
justify-content: space-between;
position: relative;
overflow: hidden;
}
.section-item .name {
font-size: 14px;
color: #666;
float: left;
}
.section-item .index {
margin-right: 5px;
}
.section-item .free {
font-size: 12px;
color: #fff;
letter-spacing: .19px;
background: #ffc210;
border-radius: 100px;
padding: 1px 9px;
margin-left: 10px;
}
.section-item .time {
font-size: 14px;
color: #666;
letter-spacing: .23px;
opacity: 1;
transition: all .15s ease-in-out;
float: right;
}
.section-item .time img {
width: 18px;
height: 18px;
margin-left: 15px;
vertical-align: text-bottom;
}
.section-item .try {
width: 86px;
height: 28px;
background: #ffc210;
border-radius: 4px;
font-size: 14px;
color: #fff;
position: absolute;
right: 20px;
top: 10px;
opacity: 0;
transition: all .2s ease-in-out;
cursor: pointer;
outline: none;
border: none;
}
.section-item:hover {
background: #fcf7ef;
box-shadow: 0 0 0 0 #f3f3f3;
}
.section-item:hover .name {
color: #333;
}
.section-item:hover .try {
opacity: 1;
}
.course-side {
width: 300px;
height: auto;
margin-left: 20px;
float: right;
}
.teacher-info {
background: #fff;
margin-bottom: 20px;
box-shadow: 0 2px 4px 0 #f0f0f0;
}
.side-title {
font-weight: normal;
font-size: 17px;
color: #4a4a4a;
padding: 18px 14px;
border-bottom: 1px solid #333;
border-bottom-color: rgba(51, 51, 51, .05);
}
.side-title span {
display: inline-block;
border-left: 2px solid #ffc210;
padding-left: 12px;
}
.teacher-content {
padding: 30px 20px;
box-sizing: border-box;
}
.teacher-content .cont1 {
margin-bottom: 12px;
overflow: hidden;
}
.teacher-content .cont1 img {
width: 54px;
height: 54px;
margin-right: 12px;
float: left;
}
.teacher-content .cont1 .name {
float: right;
}
.teacher-content .cont1 .teacher-name {
width: 188px;
font-size: 16px;
color: #4a4a4a;
padding-bottom: 4px;
}
.teacher-content .cont1 .teacher-title {
width: 188px;
font-size: 13px;
color: #9b9b9b;
white-space: nowrap;
}
.teacher-content .narrative {
font-size: 14px;
color: #666;
line-height: 24px;
}
</style>
* 2. 安装视频组件
命令: cnpm install vue-video-player
* 3. 在main.js中配置视图组件
require('video.js/dist/video-js.css');
require('vue-video-player/src/custom-theme.css');
import VideoPlayer from 'vue-video-player'
Vue.use(VideoPlayer);
* 4. 在src/router/index.js 路由文件中添加FreeCourseDetail页面的路由.
import FreeCourseDetail from "@/views/FreeCourseDetail"
{
path: '/free/detail/:id',
name: 'FreeCourseDetail',
component: FreeCourseDetail
},
:id 将路由之后的值赋值给id, 可以通过this.$route.params.id 获取值.
:名称 --> .名称
8. 视图托管
* 1. 注册七牛云https://portal.qiniu.com/
* 2. 注册之后再个人中心实名认证
* 3. 空间管理中新建空间, 访问权限设置为公开即可.
* 2. 上传视频到空间
* 3. 复制文件的连接地址
* 4. 免费课程详情页面中的视频的地址.
<script>
export default {
name: "FreeCourseDetail",
data() {
return {
playerOptions: {
...
src: "http://rcux5weit.hn-bkt.clouddn.com/bear.mp4?e=1654189473&token=XzxkEBU9Taah6BwPBiF5CcJLP4nbQ-dpJmesiGOq:F4ihGlpjjWgQKPs6CAAipL7bAdk="
...
* 5. 查看效果
9. 视频广告简介
<videoPlayer class="video-player vjs-custom-skin"
ref="videoPlayer"
:playsinline="true"
:options="playerOptions"
@play="onPlayerPlay($event)"
@pause="onPlayerPause($event)">
</videoPlayer>
methods: {
onPlayerPlay() {
console.log('视频开始播放')
},
onPlayerPause() {
console.log('视频暂停,可以打开广告了')
},
...
10. 按课程名称搜索接口
ps: 全文检索引擎: elasticsearch, java封装的一个数据库, 专注于大数据存储和搜索.
* 1. 路由
router.register('search', views.CouresSearchView, 'search')
* 2. 视图类
class CourseSearchView(GenericViewSet, ListModelMixin):
queryset = models.Course.objects.filter(is_delete=False, is_show=True)
serializer_class = serializer.CourseModelSerializer
from .paginations import PageNumberPagination
pagination_class = PageNumberPagination
from rest_framework.filters import SearchFilter
filter_backends = [SearchFilter]
search_fields = ['name']
* 3. 测试地址: http://127.0.0.1:8000/course/search/?search=linux
http://127.0.0.1:8000/course/search/ 查询全部数据
http://127.0.0.1:8000/course/search/?search=课程名称存在的文字
11. 搜索页面前台
this.$route.params 从路径中取值, 对应 --> :变量
this.$router.query 从路径?后面取值 对应 --> ?key=value
url地址: 127.0.0.1:8000/路径?xx=xx
* 1. 新建搜索详情页面组件 SearchCourse.vue
<template>
<div class="search-course course">
<Header/>
<div class="main">
<div v-if="course_list.length > 0" class="course-list">
<div class="course_total">搜索到{{course_total}}条结果</div>
<div class="course-item" v-for="course in course_list" :key="course.name">
<div class="course-image">
<img :src="course.course_img" alt="">
</div>
<div class="course-info">
<h3>
<router-link :to="'/free/detail/'+course.id">{{ course.name }}</router-link>
<span><img src="@/assets/img/avatar1.svg" alt="">{{ course.students }}人已加入学习</span>
</h3>
<p class="teacher-info">
{{ course.teacher.name }} {{ course.teacher.title }} {{ course.teacher.signature }}
<span v-if="course.sections>course.pub_sections">共{{ course.sections }}课时/已更新{{
course.pub_sections
}}课时</span>
<span v-else>共{{ course.sections }}课时/更新完成</span></p>
<ul class="section-list">
<li v-for="(section, key) in course.section_list" :key="section.name">
<span class="section-title">0{{ key + 1 }} | {{ section.name }}</span>
<span class="free" v-if="section.free_trail">免费</span></li>
</ul>
<div class="pay-box">
<div v-if="course.discount_type">
<span class="discount-type">{{ course.discount_type }}</span>
<span class="discount-price">¥{{ course.real_price }}元</span>
<span class="original-price">原价:{{ course.price }}元</span>
</div>
<span v-else class="discount-price">¥{{ course.price }}元</span>
<span class="buy-now">立即购买</span>
</div>
</div>
</div>
</div>
<div v-else style="text-align: center; line-height: 60px">
没有搜索结果
</div>
<div class="course_pagination block">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="filter.page"
:page-sizes="[2, 3, 5, 10]"
:page-size="filter.page_size"
layout="sizes, prev, pager, next"
:total="course_total">
</el-pagination>
</div>
</div>
</div>
</template>
<script>
import Header from '../components/Head'
export default {
name: "SearchCourse",
components: {
Header,
},
data() {
return {
course_list: [],
course_total: 0,
filter: {
page_size: 10,
page: 1,
search: '',
}
}
},
created() {
this.get_course()
},
watch: {
'$route.query'() {
this.get_course()
}
},
methods: {
handleSizeChange(val) {
this.filter.page = 1;
this.filter.page_size = val;
},
handleCurrentChange(val) {
this.filter.page = val;
},
get_course() {
this.filter.search = this.$route.query.word || this.$route.query.wd;
this.$axios.get(`${this.$settings.base_url}/course/search/`, {
params: this.filter
}).then(response => {
this.course_list = response.data.results;
this.course_total = response.data.count;
}).catch(() => {
this.$message({
message: "获取课程信息有误,请联系客服工作人员"
})
})
}
}
}
</script>
<style scoped>
.course {
background: #f6f6f6;
}
.course .main {
width: 1100px;
margin: 35px auto 0;
}
.course .condition {
margin-bottom: 35px;
padding: 25px 30px 25px 20px;
background: #fff;
border-radius: 4px;
box-shadow: 0 2px 4px 0 #f0f0f0;
}
.course .cate-list {
border-bottom: 1px solid #333;
border-bottom-color: rgba(51, 51, 51, .05);
padding-bottom: 18px;
margin-bottom: 17px;
}
.course .cate-list::after {
content: "";
display: block;
clear: both;
}
.course .cate-list li {
float: left;
font-size: 16px;
padding: 6px 15px;
line-height: 16px;
margin-left: 14px;
position: relative;
transition: all .3s ease;
cursor: pointer;
color: #4a4a4a;
border: 1px solid transparent;
}
.course .cate-list .title {
color: #888;
margin-left: 0;
letter-spacing: .36px;
padding: 0;
line-height: 28px;
}
.course .cate-list .this {
color: #ffc210;
border: 1px solid #ffc210 !important;
border-radius: 30px;
}
.course .ordering::after {
content: "";
display: block;
clear: both;
}
.course .ordering ul {
float: left;
}
.course .ordering ul::after {
content: "";
display: block;
clear: both;
}
.course .ordering .condition-result {
float: right;
font-size: 14px;
color: #9b9b9b;
line-height: 28px;
}
.course .ordering ul li {
float: left;
padding: 6px 15px;
line-height: 16px;
margin-left: 14px;
position: relative;
transition: all .3s ease;
cursor: pointer;
color: #4a4a4a;
}
.course .ordering .title {
font-size: 16px;
color: #888;
letter-spacing: .36px;
margin-left: 0;
padding: 0;
line-height: 28px;
}
.course .ordering .this {
color: #ffc210;
}
.course .ordering .price {
position: relative;
}
.course .ordering .price::before,
.course .ordering .price::after {
cursor: pointer;
content: "";
display: block;
width: 0px;
height: 0px;
border: 5px solid transparent;
position: absolute;
right: 0;
}
.course .ordering .price::before {
border-bottom: 5px solid #aaa;
margin-bottom: 2px;
top: 2px;
}
.course .ordering .price::after {
border-top: 5px solid #aaa;
bottom: 2px;
}
.course .ordering .price_up::before {
border-bottom-color: #ffc210;
}
.course .ordering .price_down::after {
border-top-color: #ffc210;
}
.course .course-item:hover {
box-shadow: 4px 6px 16px rgba(0, 0, 0, .5);
}
.course .course-item {
width: 1100px;
background: #fff;
padding: 20px 30px 20px 20px;
margin-bottom: 35px;
border-radius: 2px;
cursor: pointer;
box-shadow: 2px 3px 16px rgba(0, 0, 0, .1);
transition: all .2s ease;
}
.course .course-item::after {
content: "";
display: block;
clear: both;
}
.course .course-item .course-image {
float: left;
width: 423px;
height: 210px;
margin-right: 30px;
}
.course .course-item .course-image img {
max-width: 100%;
max-height: 210px;
}
.course .course-item .course-info {
float: left;
width: 596px;
}
.course-item .course-info h3 a {
font-size: 26px;
color: #333;
font-weight: normal;
margin-bottom: 8px;
}
.course-item .course-info h3 span {
font-size: 14px;
color: #9b9b9b;
float: right;
margin-top: 14px;
}
.course-item .course-info h3 span img {
width: 11px;
height: auto;
margin-right: 7px;
}
.course-item .course-info .teacher-info {
font-size: 14px;
color: #9b9b9b;
margin-top: 2px;
margin-bottom: 14px;
padding-bottom: 14px;
border-bottom: 1px solid #333;
border-bottom-color: rgba(51, 51, 51, .05);
}
.course-item .course-info .teacher-info span {
float: right;
}
.course-item .section-list::after {
content: "";
display: block;
clear: both;
}
.course-item .section-list li {
float: left;
width: 44%;
font-size: 14px;
color: #666;
padding-left: 22px;
background: url("/src/assets/img/play-icon-gray.svg") no-repeat left 4px;
margin-bottom: 15px;
}
.course-item .section-list li .section-title {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
display: inline-block;
max-width: 200px;
}
.course-item .section-list li:hover {
background-image: url("/src/assets/img/play-icon-yellow.svg");
color: #ffc210;
}
.course-item .section-list li .free {
width: 34px;
height: 20px;
color: #fd7b4d;
vertical-align: super;
margin-left: 10px;
border: 1px solid #fd7b4d;
border-radius: 2px;
text-align: center;
font-size: 13px;
white-space: nowrap;
}
.course-item .section-list li:hover .free {
color: #ffc210;
border-color: #ffc210;
}
.course-item {
position: relative;
}
.course-item .pay-box {
position: absolute;
bottom: 20px;
width: 600px;
}
.course-item .pay-box::after {
content: "";
display: block;
clear: both;
}
.course-item .pay-box .discount-type {
padding: 6px 10px;
font-size: 16px;
color: #fff;
text-align: center;
margin-right: 8px;
background: #fa6240;
border: 1px solid #fa6240;
border-radius: 10px 0 10px 0;
float: left;
}
.course-item .pay-box .discount-price {
font-size: 24px;
color: #fa6240;
float: left;
}
.course-item .pay-box .original-price {
text-decoration: line-through;
font-size: 14px;
color: #9b9b9b;
margin-left: 10px;
float: left;
margin-top: 10px;
}
.course-item .pay-box .buy-now {
width: 120px;
height: 38px;
background: transparent;
color: #fa6240;
font-size: 16px;
border: 1px solid #fd7b4d;
border-radius: 3px;
transition: all .2s ease-in-out;
float: right;
text-align: center;
line-height: 38px;
position: absolute;
right: 0;
bottom: 5px;
}
.course-item .pay-box .buy-now:hover {
color: #fff;
background: #ffc210;
border: 1px solid #ffc210;
}
.course .course_pagination {
margin-bottom: 60px;
text-align: center;
}
.course .course_total {
text-align: center;
font-size: 24px;
color: #fa6240;
margin-bottom: 10px;
}
</style>
* 2. src/router/index.js中配置路由
import Search from "@/views/Search"
{
path: '/course/search/',
name: 'Search',
component: Search
},
* 3. head组件添加一下代码
<template>
<div class="right-part">...</div>
<form class="search">
<div class="tips" v-if="is_search_tip">
<span @click="search_action('Python')">Python</span>
<span @click="search_action('Linux')">Linux</span>
</div>
<input type="text" :placeholder="search_placeholder" @focus="on_search" @blur="off_search"
v-model="search_word">
<button type="button" class="glyphicon glyphicon-search" @click="search_action(search_word)"></button>
</form>
</template>
<script>
export default {
data() {
return {
is_search_tip: true,
search_placeholder: '',
search_word: '',
}
},
methods: {
search_action(search_word) {
if (!search_word) {
this.$message('请输入要搜索的内容');
return
}
if (search_word !== this.$route.query.word) {
this.$router.push(`/course/search?word=${search_word}`);
}
this.search_word = '';
},
on_search() {
this.search_placeholder = '请输入想搜索的课程';
this.is_search_tip = false;
},
off_search() {
this.search_placeholder = '';
this.is_search_tip = true;
},
}
</script>
<style scoped>
.search {
float: right;
position: relative;
margin-top: 22px;
margin-right: 10px;
}
.search input, .search button {
border: none;
outline: none;
background-color: white;
}
.search input {
border-bottom: 1px solid #eeeeee;
}
.search input:focus {
border-bottom-color: orange;
}
.search input:focus + button {
color: orange;
}
.search .tips {
position: absolute;
bottom: 3px;
left: 0;
}
.search .tips span {
border-radius: 11px;
background-color: #eee;
line-height: 22px;
display: inline-block;
padding: 0 7px;
margin-right: 3px;
cursor: pointer;
color: #aaa;
font-size: 14px;
}
.search .tips span:hover {
color: orange;
}
</style>
* 4. 点击默认关键字跳转到 跳转到 http://localhost:8080/#/course/search?word=Linux
if (search_word !== this.$route.query.word) {
this.$router.push(`/course/search?word=${search_word}`);}
* 5. 测试(需要点击搜索图标才能搜索.)
点击搜索的时候是得到一个vue页面, vue页面通过生命周期钩子函数发送了ajax请求.
生命周期钩子通过this.$router.query 获取路径?后面取值
拼接成: http:127.0.0.1:8000/course/search/?page_size=10&page=1&search=Linux
向后端发送请求.
|