Django中drf之序列化高级用法:source和定制字段的两种方式

1 序列化高级用法之source

1.0准备数据,创建表和序列化类:

序列化类Serializer.py中:

class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    name = serializers.CharField()
    price = serializers.IntegerField(max_value=100, error_messages={'max_value': '太高了!买不起!'}, read_only=True)

class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)

表模型models.py中:

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)

    publish = models.ForeignKey(to='Publish', on_delete=models.SET_NULL, null=True)
    authors = models.ManyToManyField(to='Author')

1.1修改前端看到的字段key值 - --》source指定的必须是对象的属性

book_name = serializers.CharField(source='name')
book_price = serializers.IntegerField(source='price')

前端看到的样式:

Django中drf之序列化高级用法:source和定制字段的两种方式_第1张图片

1.2修改前端看到的value值,---》source指定的必须是对象的方法

表模型models.py中写方法:

def new_name(self):
    return '四大名著之' + self.name

序列化类Serializer.py中:

book_name = serializers.CharField(source='new_name')

前端看到的样式:

Django中drf之序列化高级用法:source和定制字段的两种方式_第2张图片

 1.3可以关联查询(得有关联关系)

publish_name = serializers.CharField(source='publish.name')
publish_addr = serializers.CharField(source='publish.addr')

2 定制字段的两种方式

2.1序列化类Serializer.py中写

# 拿出出版社的id和名字和addr,放到一个字典中
     publish_detail = serializers.SerializerMethodField()
     def get_publish_detail(self, all_books):
         return {'id': all_books.publish.id, 'name': all_books.publish.name, 'addr': all_books.publish.addr}

    # 拿出所有作者的信息 - -》多条[{name:, phone:}, {}]
     author_detail = serializers.SerializerMethodField()
    
     def get_author_detail(self, all_books):
         l = []
         author_details = all_books.authors.all()
         for i in author_details:
            l.append({'name': i.name, 'phone': i.phone})
            return l

前端看到的样式:

Django中drf之序列化高级用法:source和定制字段的两种方式_第3张图片

2.2 表模型models.py中写

序列化类Serializer.py中写

publish_detail = serializers.DictField(read_only=True)
author_list = serializers.ListField(read_only=True)


publish_id = serializers.IntegerField(write_only=True)
authors = serializers.ListField(write_only=True)

表模型models.py中写一个方法,方法名必须叫publish_detail,这个方法返回什么,这个字段的value就是什么

# 到表模型中写一个方法,方法名必须叫publish_detail,这个方法返回什么,这个字段的value就是什么
     @property
     def publish_detail(self):
         return {'id': self.publish.id, 'name': self.publish.name, 'addr': self.publish.addr}
     @property
     def author_list(self):
         l = []
         for author in self.authors.all():
             l.append({'id': author.pk, 'name': author.name, 'phone': author.phone, 'age': author.author_detail.age})
         return l

前端看到的样式:

Django中drf之序列化高级用法:source和定制字段的两种方式_第4张图片

你可能感兴趣的:(python,django)