1,创建course模型
1.1创建用户模型course
python ../manage.py startapp course
1.2 在setting.py中注册course模型(第一步)
INSTALLED_APPS = [ 'course.apps.CourseConfig', ]
1.3 syl/urls.py添加路由(第二步)
urlpatterns = [ path('course/', include('course.urls')), ]
1.4 创建 course/urls.py路由文件(第三步)
from django.urls import path, re_path from . import views urlpatterns = [ ]
2 创建表
2.1 课程主表,课程标签,课程类别,课程章,课程节
from django.db import models #抽象基类 class Base(models.Model): create_time = models.DateTimeField('创建时间', auto_now_add=True, null=True) update_time = models.DateTimeField('更新时间', auto_now=True, null=True) class Meta: abstract = True # 课程类别 class CourseType(Base): title=models.CharField("课程类别",max_length=16) sequence=models.IntegerField("展示顺序",default=10) class Meta: db_table="tb_coursetype" def __str__(self): return self.title # 课程标签 class CourseTag(Base): title=models.CharField("课程标签",max_length=16) sequence=models.IntegerField("展示顺序",default=10) class Meta: db_table="tb_coursetag" def __str__(self): return self.title # 课程 class Course(Base): STATUS=( ('0','即将上线'), ('1','已经上线'), ('2','已经下线'), ) title=models.CharField("课程名",max_length=24) desc=models.CharField("课程描述",max_length=256) img=models.ImageField("课程logo",upload_to="media",null=True) course_type=models.ForeignKey(CourseType,verbose_name="课程类别", on_delete=models.SET_NULL,default=None,null=True) course_tag=models.ManyToManyField(CourseTag,verbose_name="课程标签") status=models.CharField("课程状态",choices=STATUS,max_length=8,default="1") attention=models.IntegerField("关注人数",default=0) learner=models.IntegerField("学习人数",default=0) class Meta: db_table="tb_course" def __str__(self): return self.title # 课程章节 class Chapters(Base): title=models.CharField("章标题",max_length=24) serial_num=models.IntegerField("章节号") course=models.ForeignKey(Course,related_name='chapters',on_delete=models.SET_NULL,null=True) class Meta: db_table="tb_chapters" def __str__(self): return self.title # 课程节标题 class Sections(Base): title=models.CharField("节标题",max_length=24) serial_num=models.IntegerField("节序号") chapters=models.ForeignKey(Chapters,related_name='sections',on_delete=models.SET_NULL,null=True) learn_time=models.IntegerField("学习小时",default=1) video=models.FileField("上传视频",upload_to='videos/%Y%m%d/',blank=True,max_length=1024) seq_num=models.IntegerField("序号",default=1) class Meta: db_table='tb_sections' def __str__(self): return self.title
2.2注册后台管理 并迁移表
from django.contrib import admin # Register your models here. from . import models admin.site.register(models.CourseType) admin.site.register(models.CourseTag) admin.site.register(models.Course) admin.site.register(models.Sections) admin.site.register(models.Chapters) 迁移表 python manage.py makemigrations python manage.py migrate
2.3增加media文件配置图片,视频存放位置及展示
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.conf.urls.static import static from syl import settings urlpatterns = [ ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
1.3 测试静态文件访问
http://192.168.56.100:8888/media/media/jz.jpg
3 课程接口开发配置
3.1.路由
from rest_framework.routers import DefaultRouter # 导入DRF得DefaultRouter from . import views router = DefaultRouter() # 有根路由 router.register(r'type',views.CourseTypeViewSet) # 类别路由 router.register(r'tag', views.CourseTagViewSet) #标签路由 router.register(r'course', views.CourseViewSet) #课程路由 router.register(r'chapters', views.ChaptersViewSet) #课程章路由 router.register(r'sections', views.SectionsViewSet) #课程节路由 urlpatterns = [ ] urlpatterns += router.urls # 把两个路由列表相加
3.2 序列化
from .models import * from rest_framework import serializers # 课程类别 class CourseTypeSerializer(serializers.ModelSerializer): class Meta: model=CourseType fields="__all__" # 课程标签 class CourseTagSerializer(serializers.ModelSerializer): class Meta: model = CourseTag fields = '__all__' #节表 class SectionsSerializer(serializers.ModelSerializer): class Meta: model = Sections fields = '__all__' # 章表 class ChaptersSerializer(serializers.ModelSerializer): sections = SectionsSerializer(many=True) class Meta: model = Chapters fields = '__all__' #课程表 class CourseSerializer(serializers.ModelSerializer): # 正向查询一对多 course_type=serializers.CharField(source='course_type.title') #正向查询多对多 course_tag=serializers.SerializerMethodField(read_only=True) #反向查询 chapters=ChaptersSerializer(many=True) class Meta: model = Course fields = '__all__' # 所有字段 def get_course_tag(self,row): course_tag_obj_list=row.course_tag.all().values("id","title") return course_tag_obj_list class CourseDeepSerializer(CourseSerializer): chapters = ChaptersSerializer(many=True)
3.3视图views配置
from rest_framework import viewsets from rest_framework.pagination import PageNumberPagination from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter from course.models import * from course.serializers import * class PageNum(PageNumberPagination): page_size_query_param = 'page_size' class CourseTypeViewSet(viewsets.ModelViewSet): queryset = CourseType.objects.all() serializer_class = CourseTypeSerializer class CourseTagViewSet(viewsets.ModelViewSet): queryset = CourseTag.objects.all() serializer_class = CourseTagSerializer class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseDeepSerializer # 指定过滤方法类, 排序方法类, 一个或多个 filter_backends = (DjangoFilterBackend, OrderingFilter) # 同时支持过滤和排序 # 指定排序字段, 不设置, 排序功能不起效 ordering_fields = ('attention', 'learner', 'create_time') # 指定过滤字段, 不设置, 过滤功能不起效 filter_fields = ('title', 'desc', 'status', 'course_type', 'course_tag') # 自定义分页器 覆盖全局配置 pagination_class = PageNum def get_serializer_class(self): if self.action == 'list': return CourseSerializer else: return CourseDeepSerializer class ChaptersViewSet(viewsets.ModelViewSet): queryset = Chapters.objects.all() serializer_class = ChaptersSerializer class SectionsViewSet(viewsets.ModelViewSet): queryset = Sections.objects.all() serializer_class = SectionsSerializer
课程接口 http://192.168.56.100:8888/course/course/ 课程类别接口 http://192.168.56.100:8888/course/type/ 课程标签接口 192.168.56.100:8888/course/tag/ 课程章接口 http://192.168.56.100:8888/course/chapters/ 课程节接口 Http://192.168.56.100:8888/course/sections/