Django REST framework框架API接口序列化之简易实现

一、重点是用到 rest_framework框架的 generics脚本文件,在view视图中导入 from rest_framework import generics,定义视图类时直接继承调用generics的两个类分别是:
ListCreateAPIView,RetrieveUpdateDestroyAPIView
这两个类封装了增删改查方法


1.png

2.png

二、浅析 generics.py

  1. generics.py文件里一个最基本的类GenericAPIView(views.APIView),里面其他的类都会继承这个类,都是基于mixins模块和GenericAPIView之间的组合。


    3.png
  2. APIView是REST framework提供的所有视图的基类, 继承自Django的View。

APIView与View的不同之处:

*传入到视图方法中的是REST framework的Request对象,而不是Django的HttpRequeset对象;
*视图方法可以返回REST framework的Response对象,视图会为响应数据设置render渲染符合前端要求的格式;
*APIException异常捕获,任何APIException异常都会被捕获到,并且处理成合适的响应信息;
*在进行dispatch()分发前,会对请求进行身份认证、权限检查、流量控制。


4.png

5.png

三、源码

  1. models.py

from django.db import models

class Category(models.Model):
name = models.CharField(max_length=10,verbose_name='分类')
def _str_(self):
return self.name

class Article(models.Model):
tit = models.CharField(verbose_name='标题',max_length=100)
vum = models.IntegerField(verbose_name='浏览量')
content = models.TextField(verbose_name='内容')
category = models.ForeignKey(to=Category,on_delete=models.CASCADE,related_name='articles')
def _str_(self):
return self.tit

  1. serializers.py

from .models import Article,Category
from rest_framework import serializers

#depth深度遍历
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '_all_'
depth = 2

class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id','name','articles')
depth = 2

  1. views.py

from .models import Article,Category
from .serializers import ArticleSerializer,CategorySerializer
from rest_framework import generics
#DRF框架序列化最简写法,导入rest_framework模块的generics

class ArticleList(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

class CategoryList(generics.ListCreateAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializer
class CategoryDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializer

  1. 总路由urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
path('admin/', admin.site.urls),
path('api/',include('app02.urls')),
]

  1. 子路由urls.py

from django.urls import path
from . import views

urlpatterns = [
path('articles/',views.ArticleList.as_view()),
path('articles//',views.ArticleDetail.as_view()),
path('categories/', views.CategoryList.as_view()),
path('categories//', views.CategoryDetail.as_view()),
]

你可能感兴趣的:(Django REST framework框架API接口序列化之简易实现)