Loading

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__'

 

posted @ 2019-07-04 16:05  MrSu  阅读(826)  评论(0编辑  收藏  举报