Django框架之DRF get post put delete 使用简单示例 (利用序列化反序列化)
路由配置
# 路由 from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^PublishView/', views.PublishView.as_view()), url(r'^PublishDetailView/(?P<pk>\d+)', views.PublishDetailView.as_view()), ]
视图类配置
# views.py from django.shortcuts import render from rest_framework.views import APIView from app01 import models from app01.MySer import BookSer,PublishSer,AuthorSer from rest_framework.response import Response # Create your views here. class PublishView(APIView): def get(self,request): publish_list = models.Publish.objects.all() bs = PublishSer(publish_list, many=True) return Response(bs.data) def post(self, request): bs = PublishSer(data=request.data) if bs.is_valid(): bs.save() return Response(bs.data) else: return Response(bs.errors) class PublishDetailView(APIView): def get(self, request, pk): publish_obj = models.Publish.objects.filter(pk=pk).first() bs = PublishSer(publish_obj, many=False) return Response(bs.data) def put(self, request, pk): publish_obj = models.Publish.objects.filter(pk=pk).first() bs = PublishSer(data=request.data, instance=publish_obj) if bs.is_valid(): bs.save() return Response(bs.data) else: return Response(bs.data) def delete(self, request, pk): models.Publish.objects.filter(pk=pk).delete() return Response("")
新建的表序列化类
# MySer.py from rest_framework import serializers from app01 import models class BookSer(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__' class PublishSer(serializers.ModelSerializer): class Meta: model = models.Publish fields = '__all__' class AuthorSer(serializers.ModelSerializer): class Meta: model = models.Author fields = '__all__'
请相信自己
当我们迷茫,懒惰,退缩的时候 我们会格外的相信命运 相信一切都是命中注定
而当我们努力拼搏,积极向上时 我们会格外的相信自己
所以命运是什么呢? 它是如果你习惯它 那它就会一直左右你
如果你想挣脱它 那它就成为你的阻碍 可如果你打破了它 那它就是你人生的垫脚石!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!