在前后端分离开发中,对于RESTfulAPI设置,一般需要将查询/更新数据以JSON方式进行返回。
序列化
Model.py
from django.db import models
class User(models.Model):
username = models.CharField(verbose_name='用户名',max_length=10)
age = models.IntegerField(verbose_name='年龄')
email = models.CharField(verbose_name='邮箱',max_length=20)
View.py
from api.models import User
from api.models import userSerializer
class userView(APIView):
def get(self,request):
queryset = User.objects.all()
# 序列化
res = userSerializer(instance=queryset, many=True)
return Response({'code':200,'msg':'ok','data':res.data})
Url.py
from . import views
from django.urls import path
urlpatterns = [
path("user/",views.userView.as_view())
]
1.序列化器类(Serializer)
from rest_framework import serializers
class userSerializer(serializers.Serializer):
username = serializers.CharField()
age = serializers.CharField()
email = serializers.CharField()
2.序列化器类(ModelSerializer)
from rest_framework import serializers
class userSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
postman测试get方法
反序列化
DRF序列化器可以将来自客户端的请求数据(通常是JSON数据)转换为Python对象,以便在视图中进行处理。
from api.models import User
from api.models import userSerializer
class userView(APIView):
def post(self,request):
# 反序列化
serializer = userSerializer(data=request.query_params)
# 如果验证成功
if serializer.is_valid():
serializer.save()
return Response({'code': 200, 'msg': 'ok'})
else:
return Response({'code': 201, 'msg': 'error'})
postman测试post方法