• django-restframework-serializers


    设置URL

     
    re_path(r'^(?P<version>w+)/courselist.html$', course.CourseView.as_view({'get': 'list'})),
    re_path(r'^(?P<version>w+)/(?P<pk>d+)/courselist.html$',course.CourseView.as_view({'get': 'retrieve',})),

    serializers

    from rest_framework.viewsets import ViewSetMixin   #继承这个类后可以使用带参数的as_view()方法
    from rest_framework.views import APIView       #构建新的request和dispatch方法可以使用.data方法

     
    from rest_framework import serializers
    from luffyrestful import models
    from rest_framework.response import Response


    class CourseSerialize(serializers.ModelSerializer):

    level = serializers.CharField(source='get_level_display') #自定义序列化字段显示level字段choices的值

    class Meta:
    model = models.Course
    fields = ['id', 'title', 'course_img', 'level']


    class CourseDetailSerialize(serializers.ModelSerializer):
    level = serializers.CharField(source='course.get_level_display')
    course_img = serializers.CharField(source='course.course_img')
    title = serializers.CharField(source='course.title')
    course_section = serializers.SerializerMethodField()
    recommend = serializers.SerializerMethodField()

    class Meta:
    model = models.CourseDetail
    fields = ['title','slogan', 'why','level','course_img', 'course_section', 'recommend']

    def get_course_section(self,obj):
    queryset = obj.course.chapter_set.all()
    return [{'name': chapter_obj.name, 'num': chapter_obj.num} for chapter_obj in queryset]

    def get_recommend(self, obj):
    queryset = obj.recommend.all()
    return [{'title': course_obj.title, 'level': course_obj.get_level_display()} for course_obj in queryset]


    class CourseView(ViewSetMixin, APIView):

    def list(self, request, *args, **kwargs):
    ret = {'code': 1000, 'data': None}
    try:
    course_list = models.Course.objects.all()
    src = CourseSerialize(course_list, many=True)
    ret['data'] = src.data
    return Response(ret)
    except Exception as e:
    ret['code'] = 1001
    ret['error'] = e
    return Response(ret)

    def retrieve(self,request, *args, **kwargs):
    ret = {'code': 1000, 'data': None}
    try:
    pk = kwargs.get('pk')
    query_obj = models.CourseDetail.objects.filter(course_id=pk).first()
    src = CourseDetailSerialize(query_obj, many=False)
    ret['data'] = src.data
    return Response(ret)
    except Exception as e:
    ret['code'] = 1001
    ret['error'] = e
    return Response(ret)
  • 相关阅读:
    hdu 3666 差分约束系统
    hdu 1198农田灌溉
    常微分方程(阿諾爾德) Page 45 相空間,相流,運動,相曲線 註記
    高等微積分(高木貞治) 1.4節 例2
    常微分方程(阿諾爾德) Page 45 相空間,相流,運動,相曲線 註記
    解析函數論 Page 29 命題(2) 函數模的有界性
    高等微積分(高木貞治) 1.4節 例2
    解析函數論 Page 29 命題(1) 有界閉集上的一致連續性
    解析函數論 Page 29 命題(3) 模的下界的可達性
    解析函數論 Page 29 命題(2) 函數模的有界性
  • 原文地址:https://www.cnblogs.com/louzi/p/9710887.html
Copyright © 2020-2023  润新知