序列化类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)
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')
book_name = serializers.CharField(source='name')
book_price = serializers.IntegerField(source='price')
表模型models.py中写方法:
def new_name(self):
return '四大名著之' + self.name
序列化类Serializer.py中:
book_name = serializers.CharField(source='new_name')
publish_name = serializers.CharField(source='publish.name')
publish_addr = serializers.CharField(source='publish.addr')
# 拿出出版社的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
前端看到的样式:
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)
# 到表模型中写一个方法,方法名必须叫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
前端看到的样式: