1 2 3 4

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

     

posted @ 2019-12-19 12:00  发哥奇妙IT之旅  阅读(166)  评论(0编辑  收藏  举报