码迷,mamicode.com
首页 > 其他好文 > 详细

DRF单表序列化和反序列化

时间:2019-12-19 12:49:20      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:att   pos   serial   object   port   comm   反序列化   序列化   post   

  • 安装 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‘)

DRF单表序列化和反序列化

标签:att   pos   serial   object   port   comm   反序列化   序列化   post   

原文地址:https://www.cnblogs.com/nbzyf/p/12066945.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!