一起自学django:4.使用ModelSerializers写序列化器
首先来认识下drf即django rest framework
官方网站:http://www.djangorestframework.org/
按照我浅薄的初步认识,drf框架就是个api管理工具,不形象的说也就是——守门员
如果我们按照django的原生写法,我们需要解决模型,视图和控制三个方面,
这里有个问题,我们从哪里获得展示和操作的端口,是网页/电脑客户端/还是手机客户端呢?
drf这个守门员的作用,就是帮我们管束写好的后端,提供api给各个端口调用,
所以我们要实现的就是,通过这个api我们要能操作到我们的程序和数据
按照官方网站的相关教程导入好第三方库后
1.使用ModelSerializers构造序列化器。
在shops和goods两个应用模块路径下创建serializers.py文件
shops/serializers.py->–>-->
#从rest_framework框架导入serializers内含ModelSerializer类
from rest_framework import serializers
#从shops应用模块下的models导入Bshop表单模型
from shops.models import Bshop
#class 表单模型名+Serializer(serializers.ModelSerializer):
class BshopSerializer(serializers.ModelSerializer):
class Meta:
model = Bshop
fields = ['num','name','where','near','puttime','changetime']
goods/serializers.py->–>-->
#从rest_framework框架导入serializers内含ModelSerializer类
from rest_framework import serializers
#从goods应用模块下的models导入Bgood表单模型
from goods.models import Bgood
#class 表单模型名+Serializer(serializers.ModelSerializer):
class BgoodSerializer(serializers.ModelSerializer):
class Meta:
model = Bgood
fields = ['goodnum','goodname','style','colour','size','money','puttime','changetime']
测试一下:
把之前启动的服务器结束一下,然后在终端输入python manage.py shell
显示
PS E:\MyProjects\shop_erp> python manage.py shell
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
在箭头后面输入测试指令
#从commoditys应用模块下的serializers导入CommoditySerializer序列化器
from goods.serializers import BgoodSerializer
# 表单模型名+Serializer
serializer = BgoodSerializer()
print(repr(serializer))
测试成功,在指令发出去之后,我们写好的Bgood表单模型就会被调用,exit()
退出
2.在两个app的views.py中写入
shops/views.py
#从rest_framework导入对应方法类
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
#从shops应用模块下的models导入Bshop模型
from shops.models import Bshop
#从shops应用模块下的serializers文件中导入BshopSerializer
from shops.serializers import BshopSerializer
goods/views.py
#从rest_framework导入对应方法类
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
#从goods应用模块下的models导入Bgood模型
from goods.models import Bgood
#从goods应用模块下的serializers文件中导入BgoodSerializer
from goods.serializers import BgoodSerializer
3.然后构造我们希望通过api进行的操作方法
shops/views.py
@api_view(['GET', 'POST'])
#起名规范:models内的某个模型表单名_list
def Bshop_list(request):
"""
get请求获取信息;post请求写入信息
"""
#如果是get请求
if request.method == 'GET':
#应用模块名 = 模型表单.objects.all()
shops = Bshop.objects.all()
#序列化 = 模型表单+Serializer(对应上一行应用模块, many=True)
serializer = BshopSerializer(shops, many=True)
#返回json
return Response(serializer.data)
#如果是post传入请求
elif request.method == 'POST':
#序列化=模型表单+Serializer(传入内容)
serializer = BshopSerializer(data=request.data)
#对序列化进行操作
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#起名规范:models内的某个模型表单名_detail
@api_view(['GET', 'PUT', 'DELETE'])
def Bshop_detail(request, pk):
"""
get查询方法;put更新方法;delete删除方法
"""
try:
#给任意变量赋予 表单模型.objects.get(pk=pk)
shopshop = Bshop.objects.get(pk=pk)
#如果查询失败表单模型.DoesNotExist
except Bshop.DoesNotExist:
#返回显示结果
return Response(status=status.HTTP_404_NOT_FOUND)
#如果是get获取信息请求:集查询
if request.method == 'GET':
#序列化=模型表单+Serializer(赋值的变量)
serializer = BshopSerializer(shopshop)
#返回json结果
return Response(serializer.data)
#如果是put放入信息请求:即更新
elif request.method == 'PUT':
#序列化=模型表单+Serializer(赋值的变量,传入的内容)
serializer = BshopSerializer(shopshop, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#如果是delete删除信息请求
elif request.method == 'DELETE':
#把对应存储内容的变量给删除
shopshop.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
同样在goods/views.py写入,因为写的方法一样只有模块不一样,直接在另一个views替换,这里不再写出
4.最后,我们需要配置一下urls
最后,我们需要将这些视图联系起来,在shops应用模块下创建一个urls.py文件并写入:
shop_erp/shops/urls.py
#从django库的urls下导入path
from django.urls import path
#从应用模块shops导入刚刚写好的views
from shops import views
urlpatterns = [
#shops 应用模块即app ,对应views层的Bshop_list
path('shops/', views.Bshop_list),
#shops 应用模块+/<int:pk>/ ,对应views层的 Bshop_detail
path('shops/<int:pk>/', views.Bshop_detail),
]
shop_erp/goods/urls.py
#从django库的urls下导入path
from django.urls import path
#从应用模块goods导入刚刚写好的views
from goods import views
urlpatterns = [
#goods 应用模块即app ,对应views层的Bgood_list
path('goods/', views.Bgood_list),
#goods 应用模块+/<int:pk>/ ,对应views层的 Bgood_detail
path('goods/<int:pk>/', views.Bgood_detail),
]
5.配置整个项目的主urls.py
我们还需要连接shop_erp项目下面的主urls.py文件中的的根urlconf ,以包括我们片段应用的URL。
shop_erp/shop_erp/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
#对应的应用模块app下的分urls
path('', include('goods.urls')),
path('', include('shops.urls')),
]
6.我们来测试一下
启动服务器
python manage.py runserver
返回链接后我们查看下对应链接
http://127.0.0.1:8000/goods/
http://127.0.0.1:8000/shops/
PS E:\MyProjects\shop_erp> py manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
May 21, 2020 - 15:46:54
Django version 3.0.6, using settings 'shop_erp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
这个时候,我们就可以看到相对应的数据
我们在settings.py文件中对应配置好drf框架的设置
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema',
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
在主urls.py文件中写一个主目录
from django.contrib import admin
from django.urls import path, include
from rest_framework.documentation import include_docs_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('docs/', include_docs_urls(title="零售管理终端")),
#对应的应用模块app下的分urls
path('', include('goods.urls')),
#path('', include('goods/<int:pk>/')),
path('', include('shops.urls')),
#path('', include('shops/<int:pk>/')),
]
这里更新了from rest_framework.documentation import include_docs_urls
和path('docs/', include_docs_urls(title="零售管理终端"))
通过登录:http://127.0.0.1:8000/docs/
就可以查看到
那么我们就可以通过对应的链接来完成我们操作的目的
查询:
写入:
删除:
那么我们在后面只需要调用我们的api就能够实现对应的操作了
上一篇: typora入门手册
下一篇: Django 第九章 Admin后台系统