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)
|