模型类:
class People(models.Model):
name = models.CharField(max_length=20, verbose_name='姓名')
sex = models.CharField(max_length=5, verbose_name='性别')
money = models.IntegerField(verbose_name='身价')
ranking = models.IntegerField(verbose_name='排名')
class Meta:
verbose_name = '名人表'
verbose_name_plural = verbose_name
db_table = 'people'
def __str__(self):
return self.name
1. 配置项目
配置setting.py文件
INSTALLED_APPS = [
'rest_framework', # drf框架
'myapp', # 子应用
'corsheaders' # 跨域
]
# 配置参数,允许所有源访问
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware' # 跨域中间件
]
2. 普通序列化器
导入模块
from rest_framework import serializers
普通序列化器
# 普通序列化器!!!
class PeopleSerializer(serializers.Serializer):
# id = serializers.IntegerField()
name = serializers.CharField(max_length=20)
sex = serializers.CharField(max_length=5)
money = serializers.IntegerField()
ranking = serializers.IntegerField()
# 新增数据会调用create方法
def create(self, validated_data):
obj = People.objects.create(
**validated_data
)
# 返回新生成的ORM对象
return obj
# 修改数据需要实现update方法
# instance,要修改的ORM对象(实例)
# validated_data, 用于修改ORM对象的数据
def update(self, instance, validated_data):
instance.name = validated_data.get('name')
instance.sex = validated_data.get('sex')
instance.money = validated_data.get('money')
instance.ranking = validated_data.get('ranking')
instance.save()
# 返回修改后的ORM对象
return instance
3. 模型序列化器
导入
from rest_framework import serializers
模型序列化器
# 模型序列化器
class PeopleSerialzes2(serializers.ModelSerializer):
class Meta:
# 指定模型类
model = People
# 指定映射字段
fields = '__all__'
模型序列化器配置
class GoodsSer(serializers.ModelSerializer):
class Meta:
model = Goods
fields = '__all__' # 指明所有模型类字段
# exclude = ('createtime',) # 排除掉的字段
# read_only_fields = ('title','description') # 只用于序列化的字段
# fields = ('title','description','inventory') # 手动指明字段
# extra_kwargs = {
# 'price':{'min_value':0, 'required':True},
# } # 修改原有字段的选项参数
4. 增删改查视图代码
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import People
from myapp.serializers import PeopleSerialzes,PeopleSerialzes2
# Create your views here.
class MyView(APIView):
def get(self,request):
print(request.query_params)
return Response({'msg':'success'},status=200)
def post(self,request):
print(request.data)
return Response({'msg':'success'},status=201)
路由:
path('people/',views.PeopleView.as_view()),
class PeopleView(APIView):
# 获取所有人物信息
def get(self,request):
people = People.objects.all()
# people是要序列化的数据,many=True多个数据
# 使用序列化器 对数据进行 序列化
ser = PeopleSerialzes2(people,many=True)
# 注意:返回的是.data
return Response(ser.data,status=200)
# 添加人物信息
def post(self,request):
# 使用序列化器进行反序列化 data=request.data要反序列化的数据
ser = PeopleSerialzes2(data=request.data)
# 判断反序列化是否成功
# raise_exception=True如果出现异常会抛出异常
if ser.is_valid(raise_exception=True):
# 如果反序列化成功保存
ser.save()
# 201 添加或修改成功
return Response({'msg':'success'},status=201)
return Response({'msg':'error'})
路由:
path('people/<int:id>/',views.PeopleView2.as_view()),
class PeopleView2(APIView):
# 查询一个人物信息
def get(self,request,id):
try:
peo_data = People.objects.get(id=id)
except Exception as e:
print(e)
# 404数据不存在
return Response({'msg':'error'},status=404)
# 对ORM操作查询到的数据进行序列化
ser = PeopleSerialzes2(peo_data)
# 查询成功
return Response(ser.data,status=200)
# 修改一个人物信息
def put(self, request, id):
try:
peo_data = People.objects.get(id=id)
except Exception as e:
print(e)
# 404数据不存在
return Response({'msg': 'error'}, status=404)
# 对要更新的数据进行 反序列化
# instance=peo_data,要修改的ORM对象(实例)
# data=request.data,用于修改ORM对象的数据
ser = PeopleSerialzes2(instance=peo_data, data=request.data)
# 判断反序列化是否成功
if ser.is_valid(raise_exception=True):
# 调用.save保存
ser.save()
# 201 添加/修改成功
return Response({'msg':'success'},status=201)
return Response({'msg':'error'},status=500)
# 删除一个人物信息
def delete(self,request,id):
try:
People.objects.filter(id=id).delete()
except Exception as e:
print(e)
# 404数据不存在
return Response({'msg':'error'},status=404)
# 204删除成功
return Response({'msg':'success'},status=204)