序列化器 普通字段、一对多字段、多对多字段(正向序列化查询,反向序列化查询)

在 serializers.py中添加序列化

序列化器 普通字段、一对多字段、多对多字段(正向序列化查询,反向序列化查询)
# -*- coding: utf-8 -*-
from rest_framework import serializers
from course.models import *

class CourseTagSerializer(serializers.ModelSerializer):
    class Meta:
        model=CourseTag
        fields='__all__'
class CourseTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model=CourseType
        fields='__all__'
class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model=Course
        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 CourssesDeepSerializer(CourseSerializer):
    chapters=CourseSerializer(many=True)
course/serialiers

在course/views.py添加视图函数

序列化器 普通字段、一对多字段、多对多字段(正向序列化查询,反向序列化查询)
from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
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=CourseSerializer

    def get_serializer_class(self):
        if self.action =='list':
            return CourseSerializer
        else:
            return CourssesDeepSerializer


class SectionsViewSet(viewsets.ModelViewSet):
    queryset = Sections.objects.all()
    serializer_class=SectionsSerializer


class ChaptersViewSet(viewsets.ModelViewSet):
    queryset = Chapters.objects.all()
    serializer_class = ChaptersSerializer
course/views.py

在子路由添加路由

# -*- coding: utf-8 -*-
from django.urls import path,re_path
from rest_framework.routers import 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'sections',views.SectionsViewSet)
router.register(r'chapters',views.ChaptersViewSet)


urlpatterns = [

]
urlpatterns+=router.urls

在syl/urls.py中添加跟路由

from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from syl import settings
urlpatterns = [
  
    path('course/', include('course.urls')),

]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

 

上一篇:Django REST Framework JWT


下一篇:Django REST Framework JWT 用户的登录注册