背景
前言:
前篇django使用一,已将基本的项目、应用创建并运行;见:django使用一——规范化创建
本篇则针对ViewSet及rest_framework初使用做介绍;
闲笔:
两束平行宇宙射线射入黑盒,在人们充满欣慰的目光中,仿佛皆以为穿出是那么的简单,没人想过射线在里面行走的轨迹。宇宙的另一端,探寻者们孜孜不倦,对于他们来说,找到一丁点蛛丝马迹,说不定就能解开这个黑盒之谜,带去无限光明。
rest_framework
1、【rest_framework框架】可以很好的帮忙我们开发REST API接口,具体介绍见官网链接:rest_framework介绍
2、【django中引入】
app中注册该应用,见下:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'article'
]
3、【views.py中使用viewset】
这里前提是对应的model已经建立。
viewset则是类的高级用法,具体django已经内部封装了相关的类,参考:
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
pass
views.py
from django.shortcuts import render
from rest_framework import viewsets
from . import models as m
from . import serializers as s
# Create your views here.
class AuthorViewSet(viewsets.ModelViewSet):
queryset = m.Author.objects.all()
serializer_class = s.AuthorSerializer
filter_fields = '__all__'
ordering = ['-pk']
class ArticleViewSet(viewsets.ModelViewSet):
queryset = m.Article.objects.all()
serializer_class = s.ArticleSerializer
filter_fields = '__all__'
ordering = ['-pk']
4、【序列化】
serializers.py
from rest_framework import serializers
from . import models as m
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = m.Author
fields = '__all__'
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = m.Article
fields = '__all__'
5、【应用中添加urls.py文件并路由注册】
应用中的urls.py
from . import views
from rest_framework.routers import DefaultRouter
urlpatterns = [] # 路由列表
router = DefaultRouter() # 可以处理视图的路由器
router.register('article', views.ArticleViewSet) # 向路由器中注册视图集
router.register('author', views.AuthorViewSet) # 向路由器中注册视图集
urlpatterns += router.urls # 将路由器中的所有路由信息追加到Django的路由列表中
6、【项目urls.py中将应用路由挂钩】
项目中的urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('article.urls'))
]
7、【结果验证】访问http://localhost:8000/api/,如图:
以上相关的restful接口过程已建立,在views.py中新建对应的接口后续开发即可。