当前位置:网站首页>Unit 11 Serializers
Unit 11 Serializers
2022-08-02 14:18:00 【czy1206527605】
一.普通序列化器
1.The way normal serializers are written
1. Created in a custom applicationserializers文件
2.进入文件,Write a normal serializer file
class PeopleSerializer(serializers.Serializer):
# id = serializers.IntegerField()
name = serializers.CharField(max_length=20)
sex = serializers.CharField(max_length=20)
money = serializers.IntegerField()
ranking = serializers.IntegerField()
PS:idFields are self-contained fields,It is best to comment out when adding, deleting and modifying operations
二.模型序列化器
1.How the model serializer is written
class PeopleSerializer2(serializers.ModelSerializer):
class Meta:
model = People
fields = '__all__'
2.Use of model serializers
将viewThe normal serializer name in the view can be changed to the model serializer name
3.Configuration of the model serializer
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},
# } # 修改原有字段的选项参数
三.Normal vs. model serializers
- 序列化时,将模型类对象传入instance参数
- 序列化结果使用序列化器对象的dataproperty is obtained
- When deserializing is created,将要被反序列化的数据传入data参数
- 反序列化一定要记得先使用is_valid校验
- When deserializing an update,将要更新的数据对象传入instance参数,更新后的数据传入data参数
- Model serializers are more convenient than normal serializers,自动生成序列化映射字段,create方法等
- Association foreign key serialization,Remember to add the foreign key of the field attribute when there are manymany=True
四.视图分析(增删查改操作)
Model class example
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
Serializer example
from rest_framework import serializers
from myapp.models import People
# 普通序列化器
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
# 模型序列化器
class PeopleSerializer2(serializers.ModelSerializer):
class Meta:
# 指定模型类
model = People
# 指定映射字段
fields = '__all__'
操作的分类
- 增加一条数据
- 修改一条数据
- 查找一条数据
- 查找所有数据
- 删除一条数据
PS:其中,235需要参数 14不需要参数.Therefore, it can be achieved by designing at least two view classes
1.查询操作
- Manually serialize query operations
def get(self,request):
people = People.objects.all()
people_list = [] # 手动序列化
for peo in people:
people_dict = {
'name':peo.name,
'sex':peo.sex,
'money':peo.money,
'ranking':peo.ranking
}
people_list.append(people_dict)
return Response(people_list,status=200)
- Automatically serialize query operations
def get(self,request):
people = People.objects.all()
ser = PeopleSerializer2(people,many=True)
return Response(ser.data,status=200)
- Automatically serialize individual query operations
def get(self,reqeust,id):
try:
peo_data = People.objects.get(id=id)
except Exception as e:
print(e)
return Response({'msg':'error'},status=404)
ser = PeopleSerializer2(peo_data)
return Response(ser.data,status=200)
2.增加操作(反序列化操作)
反序列化 json->ORM格式数据
def post(self,request):
ser = PeopleSerializer2(data=request.data)
if ser.is_valid(raise_exception=True):
ser.save()
return Response({'msg':'success'},status=201)
return Response({'msg':'error'},status=400)
New data to be called when running under a normal serializercreate方法
Added under normal serializers
def create(self, validated_data):
obj = People.objects.create(
**validated_data
)
return obj
3.修改操作(反序列化)
def put(self,request,id):
try:
peo_data = People.objects.get(id=id)
except Exception as e:
print(e)
return Response({'msg': 'error'}, status=404)
ser = PeopleSerializer2(instance=peo_data,data=request.data)
if ser.is_valid(raise_exception=True):
ser.save()
return Response({'msg': 'success'}, status=201)
return Response({'msg': 'error'}, status=500)
New data to be called when running under a normal serializerupdate方法
Added under normal serializers
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
4.删除操作
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)
边栏推荐
猜你喜欢
海明校验码纠错设计原理
The 2nd China Rust Developers Conference (RustChinaConf 2021~2022) Online Conference Officially Opens Registration
目标检测场景SSD-Mobilenetv1-FPN
世界上最大的开源基金会 Apache 是如何运作的?
How does Apache, the world's largest open source foundation, work?
Sentinel源码(四)(滑动窗口流量统计)
8581 线性链表逆置
yolov5,yolov4,yolov3乱七八糟的
[ROS] The software package of the industrial computer does not compile
What are the file encryption software?Keep your files safe
随机推荐
Swagger 的使用
Unit 7 ORM table relationships and operations
redis延时队列
yolov5,yolov4,yolov3乱七八糟的
Flask上下文,蓝图和Flask-RESTful
mysql的case when如何用
[ROS]roscd和cd的区别
Unit 15 Paging, Filtering
ZABBIX配置邮件报警和微信报警
动手学ocr(一)
【Tensorflow】AttributeError: '_TfDeviceCaptureOp' object has no attribute '_set_device_from_string'
Tornado框架路由系统介绍及(IOloop.current().start())启动源码分析
You can't accept 60% slump, there is no eligible for gain of 6000% in 2021-05-27
深度学习框架pytorch快速开发与实战chapter4
第四单元 路由层
What are the file encryption software?Keep your files safe
The bad policy has no long-term impact on the market, and the bull market will continue 2021-05-19
EasyExcel 的使用
理解TCP长连接(Keepalive)
Flask请求应用上下文源码分析