課程表接口

基礎接口

序列化:course/serializers.py
from rest_framework import serializers
from .models import CourseCategory, Course, Teacher

class CourseCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = CourseCategory
        fields = ["id","name"]

class TeacherSerializer(serializers.ModelSerializer):
    """課程列表的老師信息"""
    class Meta:
        model = Teacher
        fields = ["id", "name", "role", "title", "signature", "brief", "image"]

class CourseSerializer(serializers.ModelSerializer):
    """課程列表的課程基本信息"""
    # 序列化器嵌套[被嵌套的序列化器必須聲明對應的字段爲模型原有的外鍵字段,同時這個被嵌套的序列化器必須先聲明才能進行調用!]
    # 若是嵌套的序列化器數據有多條,則須要在調用序列化器時須要聲明 many=True
    teacher = TeacherSerializer()
    class Meta:
        model = Course
        fields = ["id", "name", "course_img", "students", "sections", "pub_sections", "price", "teacher", 'section_list]
視圖:course/views.py
from rest_framework.generics import ListAPIView
from .models import CourseCategory, Course
from .serializers import CourseCategorySerializer, CourseSerializer
class CourseCategoryAPIView(ListAPIView):
    """課程分類列表接口"""
    queryset = CourseCategory.objects.filter(is_delete=False,is_show=True).order_by("orders")
    serializer_class = CourseCategorySerializer

class CourseAPIView(ListAPIView):
    """課程列表接口"""
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by("orders")
    serializer_class = CourseSerializer
路由:course/urls.py
from django.urls import path,re_path
from . import views
urlpatterns = [
    path("", views.CourseAPIView.as_view()),
    path("category/", views.CourseCategoryAPIView.as_view()),
]
接口
http://127.0.0.1:8000/course/
http://127.0.0.1:8000/course/category/

連表接口

模型演變:course/models.py
class Course(BaseModel):
    """課程"""
    course_type = (
        (0, '付費'),
        (1, 'VIP專享'),
        (2, '學位課程')
    )
    level_choices = (
        (0, '初級'),
        (1, '中級'),
        (2, '高級'),
    )
    status_choices = (
        (0, '上線'),
        (1, '下線'),
        (2, '預上線'),
    )
    name = models.CharField(max_length=128, verbose_name="課程名稱")
    course_img = models.ImageField(upload_to="course", max_length=255, verbose_name="封面圖片", blank=True, null=True)
    course_type = models.SmallIntegerField(choices=course_type, default=0, verbose_name="付費類型")
    # 使用這個字段的緣由
    brief = models.TextField(max_length=2048, verbose_name="詳情介紹", null=True, blank=True)
    level = models.SmallIntegerField(choices=level_choices, default=0, verbose_name="難度等級")
    pub_date = models.DateField(verbose_name="發佈日期", auto_now_add=True)
    period = models.IntegerField(verbose_name="建議學習週期(day)", default=7)
    attachment_path = models.FileField(upload_to="attachment", max_length=128, verbose_name="課件路徑", blank=True,
                                       null=True)
    status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="課程狀態")
    course_category = models.ForeignKey("CourseCategory", on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True,
                                        verbose_name="課程分類")
    students = models.IntegerField(verbose_name="學習人數", default=0)
    lessons = models.IntegerField(verbose_name="總課時數量", default=0)
    pub_lessons = models.IntegerField(verbose_name="課時更新數量", default=0)
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="課程原價", default=0)
    teacher = models.ForeignKey("Teacher", on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name="授課老師")

    class Meta:
        db_table = "luffy_course"
        verbose_name = "課程"
        verbose_name_plural = "課程"

    def __str__(self):
        return "%s" % self.name

    @property
    def teacher_name(self):
        """返回老師姓名"""
        return self.teacher.name

    @property
    def section_list(self):
        """課程列表的推薦課時"""
        # 獲取當前課程的全部章節
        coursechapter_list = self.coursechapters.filter(is_show=True, is_delete=False).order_by("orders")
        # 經過循環當前磕磣的全部章節,來獲取章節下面的全部課時
        data_list = []
        for coursechapter in coursechapter_list:
            # 當前章節下的全部課時
            coursesection_list = coursechapter.coursesections.filter(is_show=True, is_delete=False).order_by("orders")
            # 循環每個課時,逐個追加到data_list進行返回
            for coursesection in coursesection_list:
                if len(data_list) >= 4:
                    break
                data_list.append({
                    "id": coursesection.id,
                    "name": coursesection.name,
                    "free_trail": coursesection.free_trail,
                })

        return data_list
序列化演變:course/serializers.py
class CourseSerializer(serializers.ModelSerializer):
    """課程列表的課程基本信息"""
    # 序列化器嵌套[被嵌套的序列化器必須聲明對應的字段爲模型原有的外鍵字段,同時這個被嵌套的序列化器必須先聲明才能進行調用!]
    # 若是嵌套的序列化器數據有多條,則須要在調用序列化器時須要聲明 many=True
    teacher = TeacherSerializer()

    class Meta:
        model = Course
        fields = ["id", "name", "course_img", "students", "sections", "pub_sections", "price", "teacher", 'section_list]
相關文章
相關標籤/搜索