zoukankan      html  css  js  c++  java
  • DRF单表序列化和反序列化

    • 安装 djangorestframework

      pip install djangorestframework
    • 将rest_framework注册到app上

      INSTALLED_APPS = [
          'rest_framework',
          'app01'
          ....
      ]
    • urls

      from django.urls import path
      from . import views
      urlpatterns = [
          path('index/',views.UserView.as_view())
      ]
    • 在models.py

      from django.db import models
      
      # 用户
      class User(models.Model):
          name = models.CharField(max_length=32,unique=True,null=True)
    • 在 app01 文件下 新建 serializer.py

      from rest_framework import serializers
      from .models import User
      
      # 序列化
      class UserSerializers(serializers.ModelSerializer):
      
          class Meta:
              model = User
              fields = '__all__'
      # 反序列化        
      class UserUnSerializer(serializers.Serializer):
          name = serializers.CharField(max_length=32)
          password = serializers.CharField(max_length=255)
         # 添加数据
          def create(self,data):
              return User.objects.create(**data)
        # 更新数据
          def update(self,instance,data):
              return instance.update(**data)
    • 在 views

      from rest_framework.response import Response
      from rest_framework.views import APIView
      from . import models
      from .serializer import UserSerializers
      
      class UserView(APIView):
      
          def get(self,request):
            user = models.User.objects.all()
              # 序列化 将对象转成json串
              data = UserSerializers(user,many=True)
              return Response(data)
      
           # 添加数据
          def post(self,request):
              name = request.POST.get('name','').strip()
              password = request.POST.get('password','').strip()
              dic = {"name":name,"password":password}
              user = UserUnSerializer(data=dic)
              if user.is_valid():
                  user.save()
                  return HttpResponse('post-ok')
              return HttpResponse('post-no')
      
          # 更新数据
          def put(self,request):
              id = request.POST.get('id','0')
              obj = models.User.objects.filter(id=id)
              name = request.POST.get('name','').strip()
              dic = {"name":name}
              user = UserUnSerializer(obj,data=dic)
              if user.is_valid():
                  user.save()
                  return HttpResponse('put-ok')
              return HttpResponse('put-no')
  • 相关阅读:
    在UpdatePanel上使用FileUpload上传文件
    Android配置开发环境
    文件服务器共享目录设置(一)
    win2008R2的Hyperv安装Ubuntu
    Comodo Time Machine导致系统进不去
    sql2005生成sql2000脚本的时候出现“User.UserType: NoLogin 不是SQL Server 2005 的有效选项“ 的解决方案
    迅雷7偷偷上传文件导致机器变卡
    文件服务器共享目录设置(二)
    再谈Javascript原型继承
    a和a:link的区别
  • 原文地址:https://www.cnblogs.com/nbzyf/p/12066945.html
Copyright © 2011-2022 走看看