django rest framework案例

#models.py
from django.db import models


# Create your models here.

class Tag(models.Model):
    """
    标签表
    """
    caption = models.CharField(verbose_name='标签', max_length=32)


class Course(models.Model):
    """
    课程表
    """
    title = models.CharField(verbose_name='课程名称', max_length=32)


class Module(models.Model):
    """
    模块表
    """
    level_choices = (
        (1, '初级'),
        (2, '中级'),
        (3, '高级'),
    )
    level = models.IntegerField(verbose_name='级别', choices=level_choices, default=1)
    name = models.CharField(verbose_name='模块名称', max_length=32)
    course = models.ForeignKey(to='Course', verbose_name='课程', on_delete=models.CASCADE)


class Video(models.Model):
    """
    视频表
    """
    title = models.CharField(verbose_name='视频名称', max_length=32)
    vid = models.CharField(verbose_name='视频id', max_length=64)
    tag = models.ManyToManyField(verbose_name='标签', to='Tag')

#urls.py
from django.urls import path, re_path, include
from drf import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('drf11', views.Drf11)

urlpatterns = [
    path('index/', views.index, name='index'),

    re_path('^drf01/(?P<version>\w+)/$', views.Drf01.as_view(), name='drf01'),

    path('drf02/', views.Drf02.as_view(), name='drf02'),

    path('drf03/', views.Drf03.as_view(), name='drf03'),

    path('drf04/', views.Drf04.as_view(), name='drf04'),

    path('drf05/', views.Drf05.as_view({'get': 'list', 'post': 'create'}), name='drf05'),
    re_path('^drf05/(?P<pk>\d+)/$',
            views.Drf05.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}),
            name='drf05'),

    path('drf06/', views.Drf06.as_view({'get': 'list', 'post': 'create'}), name='drf06'),
    re_path('^drf06/(?P<pk>\d+)/$',
            views.Drf06.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}),
            name='drf06'),

    path('drf07/', views.Drf07.as_view(), name='drf07'),

    re_path('^drf08/(?P<pk>\d+)/$', views.Drf08.as_view(), name='drf08'),
    path('drf08/', views.Drf08.as_view(), name='drf08'),

    re_path('^drf09/(?P<pk>\d+)/$',
            views.Drf09.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy', 'patch': 'partial_update'}),
            name='drf09'),
    path('drf09/', views.Drf09.as_view({'get': 'list', 'post': 'create'}), name='drf09'),

    path('drf10/', views.Drf10.as_view(), name='drf10'),
    re_path('^drf10/(?P<pk>\d+)/$', views.Drf10.as_view(), name='drf10'),

    path('', include(router.urls)),

    path('drf12/', views.Drf12.as_view(), name='drf12'),
    re_path('^drf12/(?P<pk>\d+)/$', views.Drf12.as_view(), name='drf12'),

]
#views.py
from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from drf import ser, models


def index(request):
    return HttpResponse('ok')

#接口返回一个字符串含有版本。
class Drf01(APIView):
    versioning_class = URLPathVersioning

    def get(self, request, *args, **kwargs):
        data = {'version': request.version}
        return Response(data=data)

#接口返回一个xml文件的内容。
class Drf02(APIView):
    def get(self, request, *args, **kwargs):
        with open('drf/templates/abc.xml') as f:
            xml = f.read()
        # print(xml)
        return Response(data=xml)

#接口基于APIView实现对课程表的获取所有数据,增加数据。
class Drf03(APIView):
    def get(self, request, *args, **kwargs):
        result = {'status': True, 'data': {}, 'error': {}}
        querset = models.Course.objects.all()
        seri = ser.CourseSerializer(instance=querset, many=True)
        result['data'] = seri.data
        return Response(data=result)

    def post(self, request, *args, **kwargs):
        result = {'status': True, 'data': {}, 'error': {}}
        seri = ser.CourseSerializer(data=request.data)
        if seri.is_valid():
            seri.save()
        else:
            result['status'] = False
            result['error'] = seri.errors
        return Response(result)

#接口基于ListAPIView、CreateAPIView获取所有数据,增加数据。
class Drf04(ListAPIView, CreateAPIView):
    queryset = models.Course.objects.all()
    serializer_class = ser.CourseSerializer

#接口对Course表实现增删改查。
class Drf05(ModelViewSet):
    queryset = models.Course.objects.all()
    serializer_class = ser.CourseSerializer

#接口对Course表实现增删改查,列表页面的功能不去数据库获取,而去文件中获取。
class Drf06(ModelViewSet):
    queryset = models.Course.objects.all()
    serializer_class = ser.CourseSerializer

    def list(self, *args, **kwargs):
        with open('drf/file/course.txt') as f:
            data = f.read()
        return Response(data=data)

#接口基于APIView+serializer实现对模块表获取数据。显示数据,只显示id和name,只显示id、name、课程名称,只显示id、name、级别名称、课程名称。
class Drf07(APIView):
    def get(self, *args, **kwargs):
        querset = models.Module.objects.all()
        seri = ser.ModuleSerializer(instance=querset, many=True)
        return Response(seri.data)

#接口基于RetrieveAPIView, CreateAPIView实现对module表的单条数据展示、增加。
class Drf08(RetrieveAPIView, CreateAPIView):
    queryset = models.Module.objects.all()
    serializer_class = ser.ModuleSerializer

#接口基于ModelViewSet实现对Module表增删改查。
class Drf09(ModelViewSet):
    queryset = models.Module.objects.all()
    serializer_class = ser.Module09Serializer

#接口实现对Video表获取视频列表,单条视频信息。
class Drf10(RetrieveAPIView, ListAPIView):
    queryset = models.Video.objects.all()
    serializer_class = ser.VideoSerializer

#接口实现对Video表增删改查。多对多操作实现tag名称。
class Drf11(ModelViewSet):
    queryset = models.Video.objects.all()
    serializer_class = ser.Video11Serializer


class Drf12(ListAPIView, RetrieveAPIView):
    queryset = models.Module.objects.all()
    serializer_class = ser.Module09Serializer

#ser.py
from rest_framework import serializers
from drf import models


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


class ModuleSerializer(serializers.ModelSerializer):
    course_name = serializers.CharField(source='course.title')
    level_text = serializers.CharField(source='get_level_display')

    class Meta:
        model = models.Module
        # fields='__all__'
        # exclude = ['course']
        fields = ['id', 'name', 'level_text', 'course_name']


class Module09Serializer(serializers.ModelSerializer):
    class Meta:
        model = models.Module
        fields = '__all__'


class VideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Video
        fields = '__all__'


class Video11Serializer(serializers.ModelSerializer):
    tag_txt = serializers.SerializerMethodField()

    class Meta:
        model = models.Video
        fields = ['id', 'title', 'vid', 'tag', 'tag_txt']

    def get_tag_txt(self, obj):
        tag_list = obj.tag.all()
        return [row.caption for row in tag_list]

posted @ 2021-02-10 17:37  得超  阅读(83)  评论(0编辑  收藏  举报