当前位置:网站首页>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)
原网站

版权声明
本文为[czy1206527605]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/214/202208021400485056.html