Django API接口FK ManyTo Many 模板

Django API接口FK ManyTo Many  模板

 

 

Url

from django.contrib import admin
from django.urls import path, re_path
from django.urls import include

urlpatterns = [
    re_path(r^admin/, admin.site.urls),
    re_path(^api/(?P<version>[v1|v2]\w+)/, include(app01.urls)),
]

 

from django.urls import path, re_path
from django.urls import include
from app01.views import account, coursehost, newspapers

urlpatterns = [
    re_path(login/$, account.LoginView.as_view()),

    re_path(course/$, coursehost.CourseView.as_view({"get": "list"})),
    re_path(course/(?P<pk>\d+)/$, coursehost.CourseView.as_view({"get": "retrieve"})),
    re_path(rcoursecategory/$, coursehost.CourseCategoryView.as_view({get: list})),

]

 

序列化

"""
* coding: utf-8

CreateTime:2019/12/18
Version: v1
DocName: account.py
Edit: Riven

Effect: Course serializers

SourceStorageLocation: RivenShop / app01 / views / coursehost.py
Modify and add function record:
        ModifyTime:
            1.
            2.
        Add function Time :
            1.
            2.

"""

from app01 import models
from rest_framework import serializers


# Course
class CourseSerializer(serializers.ModelSerializer):
    # (0, ‘初级‘), (1, ‘中级‘), (2, ‘高级‘) Can get value
    course_type = serializers.CharField(source=get_course_type_display)
    status = serializers.CharField(source=get_status_display)
    level = serializers.CharField(source=get_level_display)

    class Meta:
        model = models.Course
        fields = [id, name, course_type, level, sub_category, degree_course, course_img, status,
                  brief, pub_date, period, attachment_path]


# CourseCategory
class CourseCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CourseCategory
        fields = __all__


class CourseDetailSerializer(serializers.ModelSerializer):
    # one2one/fk/choice  Fk inquire
    name = serializers.CharField(source=course.name)
    img = serializers.CharField(source=course.course_img)
    level = serializers.CharField(source=course.get_level_display)

    # m2m
    recommend_courses = serializers.SerializerMethodField()
    teachers = serializers.SerializerMethodField()

    # FK reverse
    coursechapter = serializers.SerializerMethodField()

    class Meta:
        model = models.CourseDetail
        fields = [id, hours, course_slogan, video_brief_link, why_study, what_to_study_brief,
                  career_improvement, prerequisite, name, level, img, recommend_courses, teachers,
                  coursechapter]

    def get_recommend_courses(self, obj):
        """acquire recommend course"""
        queryset = obj.recommend_courses.all()
        return [{id: row.id, name: row.name} for row in queryset]

    def get_teachers(self, obj):
        """acquire teachers all"""
        obj = obj.teachers.all()
        return [{id: row.id, name: row.name} for row in obj]

    def get_coursechapter(self, obj):
        """acquire chapter all base on reverse"""
        obj = obj.course.coursechapters.all()

        return [{id: row.id} for row in obj]

 

视图

"""
* coding: utf-8

CreateTime:2019/12/17
Version: v1
DocName: account.py
Edit: Riven

Effect: Supply data for Course

SourceStorageLocation: RivenShop / app01 / views / Coursehost
Modify and add function record:
        ModifyTime:
            1.
            2.
        Add function Time :
            1.
            2.

"""

from app01 import models
from serializers.course import CourseCategorySerializer, CourseDetailSerializer, CourseSerializer

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ViewSetMixin


class CourseCategoryView(ViewSetMixin, APIView):
    """
        Course main class

    """

    def list(self, request, *args, **kwargs):

        ret = {"code": 1000, "data": None}
        try:
            queryset = models.CourseCategory.objects.all()
            ser = CourseCategorySerializer(instance=queryset, many=True)
            ret[data] = ser.data
        except Exception as e:
            ret[code] = 1001
            ret[error] = 获取课程失败

        return Response(ret)


class CourseView(ViewSetMixin, APIView):

    def list(self, request, *args, **kwargs):
        """
         Course list Api

        """

        ret = {code: 1000, data: None}
        try:
            queryset = models.Course.objects.all()
            ser = CourseSerializer(instance=queryset, many=True)
            print(ser.data)
            ret[data] = ser.data

        except Exception as e:
            ret[code] = 1001
            ret[error] = 获取课程失败

        return Response(ret)

    def retrieve(self, request, *args, **kwargs):
        """

        CourseDetail api

        """

        ret = {code: 1000, data: None}

        try:
            # Acquire course id
            pk = kwargs.get(pk)
            # CourseDetail object
            obj = models.CourseDetail.objects.filter(course_id=pk).first()
            ser = CourseDetailSerializer(instance=obj, many=False)
            ret[data] = ser.data

        except Exception as e:
            ret[code] = 1001
            ret[error] = 获取课程详细失败

        return Response(ret)

Django API接口FK ManyTo Many 模板

上一篇:C# lambda 和 Linq


下一篇:C# MagicOnion 基本使用 IService ServiceBase