码迷,mamicode.com
首页 > 其他好文 > 详细

django-restframework-serializers

时间:2018-09-27 01:42:04      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:set   lse   mod   views   mode   djang   query   object   retrieve   

设置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
from rest_framework.views import APIView
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‘)

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)

django-restframework-serializers

标签:set   lse   mod   views   mode   djang   query   object   retrieve   

原文地址:https://www.cnblogs.com/louzi/p/9710887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!