DRF单表序列化和反序列化

Posted nbzyf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘)

以上是关于DRF单表序列化和反序列化的主要内容,如果未能解决你的问题,请参考以下文章

DRF一对多序列化和反序列化

drf的序列化和反序列化

DRF序列化和反序列化(二:ModelSerializer)

drf中的序列化家族

序列化和反序列化原理

drf 序列化组件