博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
路飞学城课程相关表结构
阅读量:4963 次
发布时间:2019-06-12

本文共 32533 字,大约阅读时间需要 108 分钟。

开发周期和团队?

-开发团队

    -导师后台   stark组件 +rbac 1人

    -管理后台 stark组件 +rbac 1人

    -主站

      -vue  1人

      - api    3人

  -运维(1人)

  -产品经理 (1人)

  -UI设计  (1人)

  -运营团队(1人)

  -销售(4人)

  -全职导师(2人)

  -测试 (1人)

  -签约导师()  

主站业务

- 课程            - 课程列表            - 课程详细            - 大纲、导师、推荐课程            - 价格策略            - 章节和课时            - 常见问题        - 深科技            - 文章列表            - 文章详细            - 收藏            - 评论            - 点赞        - 支付            - 购物车(4)            - 结算中心(3)            - 立即支付(1)            知识点:                - redis                - 支付宝                - 消息推送                - 构建数据结构                - 优惠券+贝里+支付宝        - 个人中心        - 课程中心

 

.-课程(13张)    -课程大类          -课程子类    -学位课          -导师          -奖学金    -专题课        -  课程详细          -常见问题        -  课时        -  作业        -  章节          -课程大纲    -价格策略

课程相关表结构

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelationfrom django.contrib.contenttypes.models import ContentTypefrom django.db.models import Qfrom django.utils.safestring import mark_safefrom django.db import modelsimport hashlib# ######################## 课程相关 ########################class CourseCategory(models.Model):    """课程大类, e.g 前端  后端..."""    name = models.CharField(max_length=64, unique=True)    def __str__(self):        return "%s" % self.name    class Meta:        verbose_name_plural = "01.课程大类"class CourseSubCategory(models.Model):    """课程子类, e.g python linux """    category = models.ForeignKey("CourseCategory")    name = models.CharField(max_length=64, unique=True)    def __str__(self):        return "%s" % self.name    class Meta:        verbose_name_plural = "02.课程子类"class DegreeCourse(models.Model):    """学位课程"""    name = models.CharField(max_length=128, unique=True)    course_img = models.CharField(max_length=255, verbose_name="缩略图")    brief = models.TextField(verbose_name="学位课程简介", )    total_scholarship = models.PositiveIntegerField(verbose_name="总奖学金(贝里)", default=40000)  # 2000 2000    mentor_compensation_bonus = models.PositiveIntegerField(verbose_name="本课程的导师辅导费用(贝里)", default=15000)    period = models.PositiveIntegerField(verbose_name="建议学习周期(days)", default=150)  # 为了计算学位奖学金    prerequisite = models.TextField(verbose_name="课程先修要求", max_length=1024)    teachers = models.ManyToManyField("Teacher", verbose_name="课程讲师")    # 用于GenericForeignKey反向查询, 不会生成表字段,切勿删除    # coupon = GenericRelation("Coupon")    # 用于GenericForeignKey反向查询,不会生成表字段,切勿删除    degreecourse_price_policy = GenericRelation("PricePolicy")    def __str__(self):        return self.name    class Meta:        verbose_name_plural = "03.学位课"class Teacher(models.Model):    """讲师、导师表"""    name = models.CharField(max_length=32)    role_choices = ((0, '讲师'), (1, '导师'))    role = models.SmallIntegerField(choices=role_choices, default=0)    title = models.CharField(max_length=64, verbose_name="职位、职称")    signature = models.CharField(max_length=255, help_text="导师签名", blank=True, null=True)    image = models.CharField(max_length=128)    brief = models.TextField(max_length=1024)    def __str__(self):        return self.name    class Meta:        verbose_name_plural = "04.导师或讲师"class Scholarship(models.Model):    """学位课程奖学金"""    degree_course = models.ForeignKey("DegreeCourse")    time_percent = models.PositiveSmallIntegerField(verbose_name="奖励档位(时间百分比)", help_text="只填百分值,如80,代表80%")    value = models.PositiveIntegerField(verbose_name="奖学金数额")    def __str__(self):        return "%s:%s" % (self.degree_course, self.value)    class Meta:        verbose_name_plural = "05.学位课奖学金"class Course(models.Model):    """专题课/学位课模块表"""    name = models.CharField(max_length=128, unique=True)    course_img = models.CharField(max_length=255)    sub_category = models.ForeignKey("CourseSubCategory")    course_type_choices = ((0, '付费'), (1, 'VIP专享'), (2, '学位课程'))    course_type = models.SmallIntegerField(choices=course_type_choices)    # 不为空;学位课的某个模块    # 为空;专题课    degree_course = models.ForeignKey("DegreeCourse", blank=True, null=True, help_text="若是学位课程,此处关联学位表")    brief = models.TextField(verbose_name="课程概述", max_length=2048)    level_choices = ((0, '初级'), (1, '中级'), (2, '高级'))    level = models.SmallIntegerField(choices=level_choices, default=1)    pub_date = models.DateField(verbose_name="发布日期", blank=True, null=True)    period = models.PositiveIntegerField(verbose_name="建议学习周期(days)", default=7)  #    order = models.IntegerField("课程顺序", help_text="从上一个课程数字往后排")    attachment_path = models.CharField(max_length=128, verbose_name="课件路径", blank=True, null=True)    status_choices = ((0, '上线'), (1, '下线'), (2, '预上线'))    status = models.SmallIntegerField(choices=status_choices, default=0)    template_id = models.SmallIntegerField("前端模板id", default=1)    # coupon = GenericRelation("Coupon")    # 用于GenericForeignKey反向查询,不会生成表字段,切勿删除    price_policy = GenericRelation("PricePolicy")    asked_question = GenericRelation("OftenAskedQuestion")    def __str__(self):        return "%s(%s)" % (self.name, self.get_course_type_display())    def save(self, *args, **kwargs):        if self.course_type == 2:            if not self.degree_course:                raise ValueError("学位课程必须关联对应的学位表")        super(Course, self).save(*args, **kwargs)    class Meta:        verbose_name_plural = "06.专题课或学位课模块"class CourseDetail(models.Model):    """课程详情页内容"""    course = models.OneToOneField("Course")    hours = models.IntegerField("课时")    course_slogan = models.CharField(max_length=125, blank=True, null=True)    video_brief_link = models.CharField(verbose_name='课程介绍', max_length=255, blank=True, null=True)    why_study = models.TextField(verbose_name="为什么学习这门课程")    what_to_study_brief = models.TextField(verbose_name="我将学到哪些内容")    career_improvement = models.TextField(verbose_name="此项目如何有助于我的职业生涯")    prerequisite = models.TextField(verbose_name="课程先修要求", max_length=1024)    recommend_courses = models.ManyToManyField("Course", related_name="recommend_by", blank=True)    teachers = models.ManyToManyField("Teacher", verbose_name="课程讲师")    def __str__(self):        return "%s" % self.course    class Meta:        verbose_name_plural = "07.课程或学位模块详细"class OftenAskedQuestion(models.Model):    """常见问题"""    content_type = models.ForeignKey(ContentType)  # 关联course or degree_course    object_id = models.PositiveIntegerField()    content_object = GenericForeignKey('content_type', 'object_id')    question = models.CharField(max_length=255)    answer = models.TextField(max_length=1024)    def __str__(self):        return "%s-%s" % (self.content_object, self.question)    class Meta:        unique_together = ('content_type', 'object_id', 'question')        verbose_name_plural = "08. 常见问题"class CourseOutline(models.Model):    """课程大纲"""    course_detail = models.ForeignKey("CourseDetail")    title = models.CharField(max_length=128)    # 前端显示顺序    order = models.PositiveSmallIntegerField(default=1)    content = models.TextField("内容", max_length=2048)    def __str__(self):        return "%s" % self.title    class Meta:        unique_together = ('course_detail', 'title')        verbose_name_plural = "09. 课程大纲"class CourseChapter(models.Model):    """课程章节"""    course = models.ForeignKey("Course", related_name='coursechapters')    chapter = models.SmallIntegerField(verbose_name="第几章", default=1)    name = models.CharField(max_length=128)    summary = models.TextField(verbose_name="章节介绍", blank=True, null=True)    pub_date = models.DateField(verbose_name="发布日期", auto_now_add=True)    class Meta:        unique_together = ("course", 'chapter')        verbose_name_plural = "10. 课程章节"    def __str__(self):        return "%s:(第%s章)%s" % (self.course, self.chapter, self.name)class CourseSection(models.Model):    """课时目录"""    chapter = models.ForeignKey("CourseChapter", related_name='coursesections')    name = models.CharField(max_length=128)    order = models.PositiveSmallIntegerField(verbose_name="课时排序", help_text="建议每个课时之间空1至2个值,以备后续插入课时")    section_type_choices = ((0, '文档'), (1, '练习'), (2, '视频'))    section_type = models.SmallIntegerField(default=2, choices=section_type_choices)    section_link = models.CharField(max_length=255, blank=True, null=True, help_text="若是video,填vid,若是文档,填link")    video_time = 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("是否可试看", default=False)    class Meta:        unique_together = ('chapter', 'section_link')        verbose_name_plural = "11. 课时"    def __str__(self):        return "%s-%s" % (self.chapter, self.name)class Homework(models.Model):    chapter = models.ForeignKey("CourseChapter")    title = models.CharField(max_length=128, verbose_name="作业题目")    order = models.PositiveSmallIntegerField("作业顺序", help_text="同一课程的每个作业之前的order值间隔1-2个数")    homework_type_choices = ((0, '作业'), (1, '模块通关考核'))    homework_type = models.SmallIntegerField(choices=homework_type_choices, default=0)    requirement = models.TextField(max_length=1024, verbose_name="作业需求")    threshold = models.TextField(max_length=1024, verbose_name="踩分点")    recommend_period = models.PositiveSmallIntegerField("推荐完成周期(天)", default=7)    scholarship_value = models.PositiveSmallIntegerField("为该作业分配的奖学金(贝里)")    note = models.TextField(blank=True, null=True)    enabled = models.BooleanField(default=True, help_text="本作业如果后期不需要了,不想让学员看到,可以设置为False")    class Meta:        unique_together = ("chapter", "title")        verbose_name_plural = "12. 章节作业"    def __str__(self):        return "%s - %s" % (self.chapter, self.title)# class CourseReview(models.Model):#     """课程评价"""#     enrolled_course = models.OneToOneField("EnrolledCourse")#     about_teacher = models.FloatField(default=0, verbose_name="讲师讲解是否清晰")#     about_video = models.FloatField(default=0, verbose_name="内容实用")#     about_course = models.FloatField(default=0, verbose_name="课程内容通俗易懂")#     review = models.TextField(max_length=1024, verbose_name="评价")#     disagree_number = models.IntegerField(default=0, verbose_name="踩")#     agree_number = models.IntegerField(default=0, verbose_name="赞同数")#     tags = models.ManyToManyField("Tags", blank=True, verbose_name="标签")#     date = models.DateTimeField(auto_now_add=True, verbose_name="评价日期")#     is_recommend = models.BooleanField("热评推荐", default=False)#     hide = models.BooleanField("不在前端页面显示此条评价", default=False)##     def __str__(self):#         return "%s-%s" % (self.enrolled_course.course, self.review)##     class Meta:#         verbose_name_plural = "13. 课程评价(购买课程后才能评价)"### class DegreeCourseReview(models.Model):#     """学位课程评价#     为了以后可以定制单独的评价内容,所以不与普通课程的评价混在一起,单独建表#     """#     enrolled_course = models.ForeignKey("EnrolledDegreeCourse")#     course = models.ForeignKey("Course", verbose_name="评价学位模块", blank=True, null=True,#                                help_text="不填写即代表评价整个学位课程", limit_choices_to={'course_type': 2})#     about_teacher = models.FloatField(default=0, verbose_name="讲师讲解是否清晰")#     about_video = models.FloatField(default=0, verbose_name="视频质量")#     about_course = models.FloatField(default=0, verbose_name="课程")#     review = models.TextField(max_length=1024, verbose_name="评价")#     disagree_number = models.IntegerField(default=0, verbose_name="踩")#     agree_number = models.IntegerField(default=0, verbose_name="赞同数")#     tags = models.ManyToManyField("Tags", blank=True, verbose_name="标签")#     date = models.DateTimeField(auto_now_add=True, verbose_name="评价日期")#     is_recommend = models.BooleanField("热评推荐", default=False)#     hide = models.BooleanField("不在前端页面显示此条评价", default=False)##     def __str__(self):#         return "%s-%s" % (self.enrolled_course, self.review)##     class Meta:#         verbose_name_plural = "14. 学位课评价(购买课程后才能评价)"class PricePolicy(models.Model):    """价格与有课程效期表"""    content_type = models.ForeignKey(ContentType)  # 关联course or degree_course    object_id = models.PositiveIntegerField()    content_object = GenericForeignKey('content_type', 'object_id')    # course = models.ForeignKey("Course")    valid_period_choices = ((1, '1天'), (3, '3天'),                            (7, '1周'), (14, '2周'),                            (30, '1个月'),                            (60, '2个月'),                            (90, '3个月'),                            (180, '6个月'), (210, '12个月'),                            (540, '18个月'), (720, '24个月'),                            )    valid_period = models.SmallIntegerField(choices=valid_period_choices)    price = models.FloatField()    class Meta:        unique_together = ("content_type", 'object_id', "valid_period")        verbose_name_plural = "15. 价格策略"    def __str__(self):        return "%s(%s)%s" % (self.content_object, self.get_valid_period_display(), self.price)
models.py
a. 查看所有学位课并打印学位课名称以及授课老师obj = models.DegreeCourse.objects.values("name","teachers__name")print(obj)b. 查看所有学位课并打印学位课名称以及学位课的奖学金obj = models.DegreeCourse.objects.all().values("name","total_scholarship")print(obj)c. 展示所有的专题课 obj = models.Course.objects.filter(degree_course__isnull=True)d. 查看id=1的学位课对应的所有模块名称 obj = models.Course.objects.filter(id=1).values("name","degree_course")e. 获取id=1的专题课,并打印:课程名、级别(中文)、why_study、what_to_study_brief、所有recommend_coursesobj = models.Course.objects.filter(degree_course__isnull=True,id=1).values("name","level","coursedetail__why_study",                                                "coursedetail__what_to_study_brief",                                                "coursedetail__recommend_courses")                                                f. 获取id=1的专题课,并打印该课程相关的所有常见问题 obj = models.Course.objects.filter(id=1)for i in obj:    print(i.asked_question.all())    g. 获取id=1的专题课,并打印该课程相关的课程大纲obj = models.CourseDetail.objects.filter(id=1).values("courseoutline__title")print(obj)h. 获取id=1的专题课,并打印该课程相关的所有章节obj = models.Course.objects.filter(id=1).values("coursechapters__name")print(obj)i.  获取id=1的专题课,并打印该课程相关的所有的价格策略 obj = models.Course.objects.filter(id=1).values("coursechapters__name","coursechapters__coursesections__name")print(obj)
ORM对课程表的查询

查询:

from django.conf.urls import urlfrom api import viewsurlpatterns = [    url(r'index/$', views.CheckView.as_view()),]查看所有学位课并打印学位课名称以及授课老师views.pyfrom django.shortcuts import render,HttpResponsefrom api import modelsfrom django.views import View# Create your views here.class CheckView(View):    """    练习题相关    """    def get(self, request):        # a.查看所有学位课并打印学位课名称以及授课老师        degree_list = models.DegreeCourse.objects.all().values('name', 'teachers__name')        print(degree_list)        return HttpResponse('ok')http://127.0.0.1:8000/api/index/结果:
第二种写法:class CheckView(View): """ 练习题相关 """ def get(self, request): # a.查看所有学位课并打印学位课名称以及授课老师 queryset = models.DegreeCourse.objects.all() for row in queryset: print(row.name,row.teachers.all()) return HttpResponse('ok')查看所有学位课并打印学位课名称以及学位课的奖学金class CheckView(View): """ 练习题相关 """ def get(self, request): # b.查看所有学位课并打印学位课名称以及学位课的奖学金 c_obj=models.DegreeCourse.objects.all() for i in c_obj: # 利用degreecourse_price_policy字段进行反向查询 print(i.name,i.degreecourse_price_policy.all().values('price')) return HttpResponse('ok')第二种写法class CheckView(View): """ 练习题相关 """ def get(self, request): # b.查看所有学位课并打印学位课名称以及学位课的奖学金 degree_list = models.DegreeCourse.objects.all() for row in degree_list: print(row.name) scholarships = row.scholarship_set.all() for item in scholarships: print('------>',item.time_percent,item.value) 展示所有的专题课class CheckView(View): """ 练习题相关 """ def get(self, request): # c. 展示所有的专题课 c_obj = models.Course.objects.filter(degree_course__isnull=True) print(c_obj) return HttpResponse('ok')查看id=1的学位课对应的所有模块名称class CheckView(View): """ 练习题相关 """ def get(self, request): # d. 查看id=1的学位课对应的所有模块名称 obj = models.DegreeCourse.objects.filter(id=1).values('course__name') print(obj) return HttpResponse('ok')获取id = 1的专题课,并打印:课程名、级别(中文)、why_study、what_to_study_brief、所有recommend_coursesclass CheckView(View): """ 练习题相关 """ def get(self, request): # e. 获取id = 1的专题课,并打印:课程名、级别(中文)、why_study、what_to_study_brief、所有recommend_courses c_obj = models.Course.objects.filter(id=1) print(c_obj.values('name')) print(c_obj.first().get_level_display()) print(c_obj.values('coursedetail__why_study')) print(c_obj.values('coursedetail__what_to_study_brief')) print(c_obj.values('coursedetail__recommend_courses')) return HttpResponse('ok')第二种写法:。。。获取id = 1的专题课,并打印该课程相关的所有常见问题class CheckView(View): """ 练习题相关 """ def get(self, request): # f. 获取id = 1的专题课,并打印该课程相关的所有常见问题 c_obj = models.Course.objects.filter(id=1).first() # 利用asked_question字段进行反向查询 print(c_obj.asked_question.all().values('question')) return HttpResponse('ok')第二种写法class CheckView(View): """ 练习题相关 """ def get(self, request): # f. 获取id = 1的专题课,并打印该课程相关的所有常见问题 obj = models.Course.objects.get(id=1) ask_list = obj.asked_question.all() for item in ask_list: print(item.question) return HttpResponse('ok')获取id = 1的专题课,并打印该课程相关的课程大纲class CheckView(View): """ 练习题相关 """ def get(self, request): # g.获取id = 1的专题课,并打印该课程相关的课程大纲 c_obj = models.Course.objects.filter(id=1) print(c_obj.values('coursedetail__courseoutline__title')) return HttpResponse('ok')第二种写法class CheckView(View): """ 练习题相关 """ def get(self, request): # g.获取id = 1的专题课,并打印该课程相关的课程大纲 obj = models.Course.objects.get(id=1) outline_list = obj.coursedetail.courseoutline_set.all() for item in outline_list: print(item.title,item.content) return HttpResponse('ok')获取id = 1的专题课,并打印该课程相关的所有章节class CheckView(View): """ 练习题相关 """ def get(self, request): # h.获取id = 1的专题课,并打印该课程相关的所有章节 c_obj = models.Course.objects.filter(id=1) print(c_obj.values('coursechapter__name')) return HttpResponse('ok')第二种写法class CheckView(View): """ 练习题相关 """ def get(self, request): # h.获取id = 1的专题课,并打印该课程相关的所有章节 obj = models.Course.objects.get(id=1) chapter_list = obj.coursechapter_set.all() # 默认obj.表名_set.all() for item in chapter_list: print(item.name) return HttpResponse('ok')获取id = 1的专题课,并打印该课程相关的所有课时class CheckView(View): """ 练习题相关 """ def get(self, request): # i.获取id = 1的专题课,并打印该课程相关的所有课时 c_obj = models.Course.objects.filter(id=1) for i in c_obj.values('coursechapter__chapter','coursechapter__name'): print(i.get('coursechapter__chapter'),i.get('coursechapter__name')) a_obj=models.CourseChapter.objects.filter(name=i.get('coursechapter__name')) for j in a_obj.values('coursesection__name'): print(' ',j.get('coursesection__name')) return HttpResponse('ok')第二种写法class CheckView(View): """ 练习题相关 """ def get(self, request): # i.获取id = 1的专题课,并打印该课程相关的所有课时 obj = models.Course.objects.get(id=1) chapter_list = obj.coursechapter_set.all() for chapter in chapter_list: print(chapter.name,chapter.coursesection_set.all()) return HttpResponse('ok')

 

所有视图都集中在views.py中,扩展不方便。

删除views.py,并创建目录views

在views目录里面创建course.py,它表示和课程相关的视图

注意:视图名最好加上View,这是约定俗成的

views下的couse.py

from django.shortcuts import render,HttpResponsefrom api import modelsfrom rest_framework.views import APIViewclass CourseView(APIView):    def get(self,request,*args,**kwargs):        return HttpResponse('ok')
course.py
from django.conf.urls import urlfrom api.views import courseurlpatterns = [    url(r'course/$', course.CourseView.as_view()),]
url

接口API的编写

from django.conf.urls import urlfrom api.views import course,degreecourseurlpatterns = [    url(r'courses/$',course.CoursesView.as_view()),    url(r'courses/(?P
\d+)/$',course.CourseDetailView.as_view()), url(r'courses/thematic/$',course.CourseThematicView.as_view()), url(r'courses/module/(?P
\d+)/$',course.CourseModuleView.as_view()), url(r'courses/faq/(?P
\d+)/$',course.CourseFAQView.as_view()), url(r'courses/outline/(?P
\d+)/$',course.CourseOutlineView.as_view()), url(r'courses/chapter/(?P
\d+)/$',course.CourseChapterView.as_view()), url(r'degreecourse/$',degreecourse.DegreeCourseView.as_view()), url(r'degreecourse/teachers/$',degreecourse.DegreeCourseTeachersView.as_view()), url(r'degreecourse/scholarship/$',degreecourse.DegreeCourseScholarshipView.as_view()),]
url.py
from rest_framework import serializersfrom api import modelsclass CourseModelSerializer(serializers.ModelSerializer):  # 所有课程    level_name = serializers.CharField(source='get_level_display')    hours = serializers.CharField(source='coursedetail.hours')    course_slogan = serializers.CharField(source='coursedetail.course_slogan')    recommend_courses = serializers.SerializerMethodField()    class Meta:        model = models.Course        fields = ['id','name','level_name','hours','course_slogan','recommend_courses']    def get_recommend_courses(self,row):        recommend_list = row.coursedetail.recommend_courses.all()        return [ {
'id':item.id,'name':item.name} for item in recommend_list]class CourseThematicModelSerializer(serializers.ModelSerializer): # 所有的专题课 level_name = serializers.CharField(source='get_level_display') course_type = serializers.CharField(source='get_course_type_display') status = serializers.CharField(source='get_status_display') degree_course = serializers.CharField(source='degree_course.total_scholarship') class Meta: model = models.Course fields = '__all__'class CourseModuleModelSerializer(serializers.ModelSerializer): # 所有的专题课 degree_course = serializers.CharField(source='degree_course.name') class Meta: model = models.Course fields = ['id','degree_course']class CourseDetailModelSerializer(serializers.ModelSerializer): # 具体id的学位课对应的所有模块名称 level_name = serializers.CharField(source='get_level_display') why_study = serializers.CharField(source='coursedetail.why_study') what_to_study_brief = serializers.CharField(source='coursedetail.what_to_study_brief') recommend_courses = serializers.SerializerMethodField() price_strategy = serializers.SerializerMethodField() class Meta: model = models.Course fields = ['id','name','level_name','why_study','what_to_study_brief','recommend_courses','price_strategy'] def get_recommend_courses(self,row): recommend_list = row.coursedetail.recommend_courses.all() return [ {
'id':item.id,'name':item.name} for item in recommend_list] def get_price_strategy(self,row): price_list = row.price_policy.all() return [{
'id': item.id, 'valid_period': item.valid_period,'price': item.price} for item in price_list]class CourseFAQModelSerializer(serializers.ModelSerializer): # 具体id专题课程相关的所有常见问题 asked_question = serializers.SerializerMethodField() class Meta: model = models.Course fields = ['id','name', 'asked_question'] def get_asked_question(self, row): faq_list = row.asked_question.all() return [{
'id': item.id, 'question': item.question, 'answer': item.answer} for item in faq_list]class CourseOutlineModelSerializer(serializers.ModelSerializer): # 具体id课程相关的课程大纲 asked_question = serializers.SerializerMethodField() class Meta: model = models.Course fields = ['id', 'name', 'asked_question'] def get_asked_question(self, row): outline_list = row.coursedetail.courseoutline_set.all() return [{
'id': item.id, 'title': item.title, 'content': item.content} for item in outline_list]class CourseChapterModelSerializer(serializers.ModelSerializer): # 具体id课程相关的所有章节 chapter = serializers.SerializerMethodField() class Meta: model = models.Course fields = ['id', 'name', 'chapter'] def get_chapter(self, row): chapter_list = row.coursechapter_set.all() return [{
'id': item.id, 'name': item.name} for item in chapter_list]
course.py
from rest_framework import serializersfrom api import modelsclass DegreeCourseModelSerializer(serializers.ModelSerializer):  # 学位课所有信息    class Meta:        model = models.DegreeCourse        fields = '__all__'class DegreeCourseTeachersModelSerializer(serializers.ModelSerializer):  # 学位课的老师    teachers = serializers.SerializerMethodField()    class Meta:        model = models.DegreeCourse        fields = ['name','teachers']    def get_teachers(self,row):        teachers_list = row.teachers.all()        return [ {
'id':item.id,'name':item.name} for item in teachers_list]class DegreeCourseScholarshipModelSerializer(serializers.ModelSerializer): # 学位课的奖学金 degreecourse_price_policy = serializers.SerializerMethodField() class Meta: model = models.DegreeCourse fields = ['name','degreecourse_price_policy'] def get_degreecourse_price_policy(self,row): scholarships = row.scholarship_set.all() return [ {
'id':item.id,'time_percent':item.time_percent,'value':item.value} for item in scholarships]
degreecourse.py
from api.utils.response import BaseResponsefrom rest_framework.pagination import PageNumberPaginationclass SerializedData(object):  # 序列化通用格式数据    def __init__(self,request,queryset,serializer_class):        self.request = request        self.queryset = queryset        self.serializer_class = serializer_class    def get_data(self):        ret = BaseResponse()        try:            # 从数据库获取数据            queryset = self.queryset.order_by('id')            # 分页            page = PageNumberPagination()            course_list = page.paginate_queryset(queryset, self.request, self)            # 分页之后的结果执行序列化            ser = self.serializer_class(instance=course_list, many=True)            ret.data = ser.data        except Exception as e:            print(e)            ret.code = 500            ret.error = '获取数据失败'        return ret.dict
封装序列化方法并分页
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.versioning import URLPathVersioningfrom rest_framework.pagination import PageNumberPaginationfrom api import modelsfrom api.serializers.course import CourseModelSerializer, CourseThematicModelSerializer, CourseModuleModelSerializer, \    CourseDetailModelSerializer,CourseFAQModelSerializer,CourseOutlineModelSerializer,CourseChapterModelSerializerfrom api.utils.response import BaseResponsefrom api.utils.serialization_general import SerializedDataclass CoursesView(APIView):  # 所有课程,分页展示,每页1个    def get(self, request, *args, **kwargs):        # response = {'code':1000,'data':None,'error':None}        queryset = models.Course.objects.all()        serializer_class = CourseModelSerializer        data = SerializedData(request,queryset,serializer_class).get_data()        return Response(data)class CourseDetailView(APIView):  # 课程详情    def get(self, request, pk, *args, **kwargs):        queryset = models.Course.objects.filter(id=pk)        serializer_class = CourseDetailModelSerializer        data = SerializedData(request, queryset, serializer_class).get_data()        return Response(data)class CourseThematicView(APIView):  # 所有的专题课    def get(self, request, *args, **kwargs):        queryset = models.Course.objects.all()        serializer_class = CourseThematicModelSerializer        data = SerializedData(request, queryset, serializer_class).get_data()        return Response(data)class CourseModuleView(APIView):  # 具体id的学位课对应的所有模块名称    def get(self, request, pk, *args, **kwargs):        queryset = models.Course.objects.filter(degree_course_id=pk)        serializer_class = CourseModuleModelSerializer        data = SerializedData(request, queryset, serializer_class).get_data()        return Response(data)class CourseFAQView(APIView):  # 具体id的课程相关的所有常见问题    def get(self, request, pk, *args, **kwargs):        queryset = models.Course.objects.filter(id=pk)        serializer_class = CourseFAQModelSerializer        data = SerializedData(request, queryset, serializer_class).get_data()        return Response(data)class CourseOutlineView(APIView):  # 具体id课程相关的课程大纲    def get(self, request, pk, *args, **kwargs):        queryset = models.Course.objects.filter(id=pk)        serializer_class = CourseOutlineModelSerializer        data = SerializedData(request, queryset, serializer_class).get_data()        return Response(data)class CourseChapterView(APIView):  # 具体id课程相关的所有章节    def get(self, request, pk, *args, **kwargs):        queryset = models.Course.objects.filter(id=pk)        serializer_class = CourseChapterModelSerializer        data = SerializedData(request, queryset, serializer_class).get_data()        return Response(data)
course.py序列化并分页
from rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework.versioning import URLPathVersioningfrom rest_framework.pagination import PageNumberPaginationfrom api import modelsfrom api.serializers.degreecourse import DegreeCourseModelSerializer,DegreeCourseTeachersModelSerializerfrom api.serializers.degreecourse import DegreeCourseScholarshipModelSerializerfrom api.utils.response import BaseResponseclass DegreeCourseView(APIView):  # 所有学位课    def get(self,request,*args,**kwargs):        # response = {'code':1000,'data':None,'error':None}        ret = BaseResponse()        try:            # 从数据库获取数据            queryset = models.DegreeCourse.objects.all()            # 分页            page = PageNumberPagination()            course_list = page.paginate_queryset(queryset,request,self)            # 分页之后的结果执行序列化            ser = DegreeCourseModelSerializer(instance=course_list,many=True)            ret.data = ser.data        except Exception as e:            ret.code = 500            ret.error = '获取数据失败'        return Response(ret.dict)class DegreeCourseTeachersView(APIView):  # 学位课对应的老师    def get(self, request, *args, **kwargs):        ret = BaseResponse()        try:            # 从数据库获取数据            # 防止出现UnorderedObjectListWarning: Pagination may yield...            queryset = models.DegreeCourse.objects.get_queryset().order_by('id')            print(queryset)            # 分页            page = PageNumberPagination()            course_list = page.paginate_queryset(queryset, request, self)            # 分页之后的结果执行序列化            ser = DegreeCourseTeachersModelSerializer(instance=course_list, many=True)            print(ser.data)            ret.data = ser.data        except Exception as e:            print(e)            ret.code = 500            ret.error = '获取数据失败'        return Response(ret.dict)class DegreeCourseScholarshipView(APIView):  # 学位课对应的老师    def get(self, request, *args, **kwargs):        ret = BaseResponse()        try:            # 从数据库获取数据            # 防止出现UnorderedObjectListWarning: Pagination may yield...            queryset = models.DegreeCourse.objects.get_queryset().order_by('id')            print(queryset)            # 分页            page = PageNumberPagination()            course_list = page.paginate_queryset(queryset, request, self)            # 分页之后的结果执行序列化            ser = DegreeCourseScholarshipModelSerializer(instance=course_list, many=True)            print(ser.data)            ret.data = ser.data        except Exception as e:            print(e)            ret.code = 500            ret.error = '获取数据失败'        return Response(ret.dict)
degreecourse.py序列化并分页

访问以下url:

查看所有学位课并打印学位课名称以及授课老师

http://127.0.0.1:8000/api/v1/degreecourse/teachers/

查看所有学位课并打印学位课名称以及学位课的奖学金

http://127.0.0.1:8000/api/v1/degreecourse/scholarship/

展示所有的专题课

http://127.0.0.1:8000/api/v1/courses/thematic/

 查看id=1的学位课对应的所有模块名称

http://127.0.0.1:8000/api/v1/courses/module/1/

获取id = 1的专题课,并打印:课程名、级别(中文)、why_study、what_to_study_brief、所有recommend_courses

http://127.0.0.1:8000/api/v1/courses/1/

获取id = 1的专题课,并打印该课程相关的所有常见问题

http://127.0.0.1:8000/api/v1/courses/faq/1/

 coursedetail获取id = 1的专题课,并打印该课程相关的课程大纲

http://127.0.0.1:8000/api/v1/courses/outline/1/

获取id = 1的专题课,并打印该课程相关的所有章节

http://127.0.0.1:8000/api/v1/courses/chapter/1/

 

转载于:https://www.cnblogs.com/weidaijie/p/10506361.html

你可能感兴趣的文章
清除浮动
查看>>
PayPal(贝宝)支付接口、文档、IPN
查看>>
ORACLE 10G R2_执行计划中cost cardinality bytes cpu_cost io_cost解释
查看>>
本地存储
查看>>
MP3的播放与停止
查看>>
牛客(59)按之字形顺序打印二叉树
查看>>
JavaScript 图表库 xCharts
查看>>
Android项目的目录结构
查看>>
C++中“引用”的底层实现
查看>>
Spring Cloud与微服务构建:微服务简介
查看>>
Babel 是干什么的
查看>>
cocos2dx-3.0(8)------Label、LabelTTF、LabelAtlas、LabelBMFont使用之法
查看>>
CODE[VS] 1842 递归第一次
查看>>
20180418小测
查看>>
数字三角形
查看>>
NGUI 减少drawcall规则
查看>>
三元表达,匿名函数
查看>>
前端笔记-基础笔记
查看>>
【LeetCode & 剑指offer刷题】查找与排序题6:33. Search in Rotated Sorted Array(系列)
查看>>
GNU/Linux超级本ZaReason Ultralap 440体验
查看>>