zoukankan      html  css  js  c++  java
  • 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__'
  • 相关阅读:
    java线程池实践
    JAVA中间件(middleware)模式
    [开源]制作docker镜像不依赖linux和Docker环境
    利用浏览器favicon的缓存机制(F-Cache)生成客户端浏览器唯一指纹
    Docker镜像构建原理解析(不装docker也能构建镜像)
    ORM框架对分表分库之分库和分表指定不同的字段
    volatile的内存屏障的坑
    go和python的比较,获取当前时间是今年第几个星期
    c++学生管理系统
    c++学生管理系统(三)
  • 原文地址:https://www.cnblogs.com/suguangti/p/11133022.html
Copyright © 2011-2022 走看看