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

rest framwork 练习

时间:2018-10-03 22:59:22      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:erb   结果   mode   int   model   返回   models   max   default   

models.py

from django.db import models

class Course(models.Model):
    """
    课程表
    """
    title = models.CharField(verbose_name=‘课程名称‘,max_length=32)
    course_img = models.CharField(verbose_name=‘课程图片‘,max_length=64)
    level_choices = (
        (1,‘初级‘),
        (2,‘中级‘),
        (3,‘高级‘),
    )
    level = models.IntegerField(verbose_name=‘课程难易程度‘,choices=level_choices,default=1)

    def __str__(self):
        return self.title

class CourseDetail(models.Model):
    """
    课程详细
    """
    course = models.OneToOneField(to=‘Course‘)
    slogon = models.CharField(verbose_name=‘口号‘,max_length=255)
    why = models.CharField(verbose_name=‘为什么要学?‘,max_length=255)
    recommend_courses = models.ManyToManyField(verbose_name=‘推荐课程‘,to=‘Course‘,related_name=‘rc‘)

    def __str__(self):
        return "课程详细:"+self.course.title

class Chapter(models.Model):
    """
    章节
    """
    num =  models.IntegerField(verbose_name=‘章节‘)
    name = models.CharField(verbose_name=‘章节名称‘,max_length=32)
    course = models.ForeignKey(verbose_name=‘所属课程‘,to=‘Course‘)

    def __str__(self):
        return self.name

urls.py

from django.conf.urls import url,include

from api.views import course


urlpatterns = [

    url(r‘^course/$‘, course.CourseView.as_view({‘get‘:‘list‘})),
    url(r‘^course/(?P<pk>\d+)$‘, course.CourseView.as_view({‘get‘:‘retrieve‘})),

    url(r‘^test$‘, course.test),
]

course.py

from rest_framework.views import APIView
from rest_framework.response import Response
from api import models

from rest_framework import serializers

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Course
        fields = "__all__"


class CourseDetailSerializer(serializers.ModelSerializer):

    # one2one/fk/choice
    title = serializers.CharField(source=‘course.title‘)
    img = serializers.CharField(source=‘course.course_img‘)
    level = serializers.CharField(source=‘course.get_level_display‘)

    # m2m
    recommends = serializers.SerializerMethodField()

    class Meta:
        model = models.CourseDetail
        fields = [‘course‘,‘title‘,‘img‘,‘level‘,‘slogon‘,‘why‘,‘recommends‘]


    def get_recommends(self,obj):
        # 获取推荐的所有课程
        queryset = obj.recommend_courses.all()

        return [{‘id‘:row.id,‘title‘:row.title} for row in queryset]

# View
# APIView
# GenericAPIView
from rest_framework.viewsets import GenericViewSet,ViewSetMixin,ModelViewSet
class CourseView(ViewSetMixin,APIView):

    def list(self,request,*args,**kwargs):
        """
        课程列表接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = {‘code‘:1000,‘data‘:None}

        try:
            queryset = models.Course.objects.all()
            ser = CourseSerializer(instance=queryset,many=True)
            ret[‘data‘] = ser.data
        except Exception as e:
            ret[‘code‘] = 1001
            ret[‘error‘] = ‘获取课程失败‘

        return Response(ret)

    def retrieve(self,request,*args,**kwargs):
        """
        课程详细接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = {‘code‘: 1000, ‘data‘: None}

        try:
            # 课程ID=2
            pk = kwargs.get(‘pk‘)

            # 课程详细对象
            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)


def test(request,*args,**kwargs):
    from django.shortcuts import HttpResponse
    obj = models.Course.objects.filter(id=2).first()
    print(obj.title)
    print(obj.level) #
    print(obj.get_level_display() ) #
    return HttpResponse(‘...‘)

 

访问  

http://127.0.0.1:8000/api/v1/course/  

  

返回结果如下

技术分享图片

访问  

http://127.0.0.1:8000/api/v1/course/1  

  

返回结果如下

技术分享图片

 

  

 

rest framwork 练习

标签:erb   结果   mode   int   model   返回   models   max   default   

原文地址:https://www.cnblogs.com/crazymagic/p/9738954.html

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