重新学习serializer

main
RogerWork 1 year ago
parent face1c8301
commit ef779f7590
  1. 40
      apps/music/serializer.py

@ -3,13 +3,43 @@ from rest_framework import serializers, fields
from apps.music.models import *
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ('id', 'artist', 'name', 'release_date', 'num_stars')
class AlbumSerializer(serializers.Serializer):
# 设置外键PrimaryKeyRelatedField
artist = serializers.PrimaryKeyRelatedField(label='音乐家', queryset=Musician.objects.all(), many=False,
allow_null=False)
name = serializers.CharField(label='专辑名', required=True, max_length=10)
# 修改字段名称并映射数据模型字段,source为指定模型的字段的字符串形式
publish_date = serializers.DateField(label='发行日期', required=False, source='Album.release_date')
num_stars = serializers.IntegerField(label='好评度')
class MusicianSerializer(serializers.Serializer):
first_name = serializers.CharField(max_length=20, required=True)
last_name = serializers.CharField(max_length=20, required=True)
instrument = serializers.CharField(max_length=50)
# 根据外键的关联关系,将AlbumNameSerializer做为扩展信息
album_musician = AlbumSerializer(many=True)
# 重写create方法
def create(self, validated_data):
albums_data = validated_data.pop('album_musician')
musician = Musician.objects.create(**validated_data)
# 插入专辑数据,artist为上一步中插入后返回的对象
for album in albums_data:
Album.objects.create(artist=musician, **album)
return musician
def update(self, instance, validated_data):
pass
# class AlbumModelSerializer(serializers.ModelSerializer):
# class Meta:
# model = Album
# fields = ('id', 'artist', 'name', 'release_date', 'num_stars')
class MusicianSerializer(serializers.ModelSerializer):
class MusicianModelSerializer(serializers.ModelSerializer):
# album_musician = AlbumSerializer(read_only=True, many=True) # 定义只读外键字段后在fields中添加此键
album_musician = AlbumSerializer(many=True) # 定义只读外键字段后在fields中添加此键,如果需要写入create和update方法,则不应设置readonly

Loading…
Cancel
Save