我只是按照文档测试从这里编写嵌套的序列化程序
http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
以下是我的测试代码
print(data_to_save)
my_as = AlbumSerializer(data=data_to_save)
my_as.is_valid()
print(my_as.validated_data)
my_as.save()
data_to_save就是这个
{'album_name': 'Peter ABC', 'artist': 'Peter', 'tracks': [OrderedDict([('order', 1), ('title', 'song 1'), ('duration', 11)]),
OrderedDict([('order',2),('title','song 2'),('duration',11)])}}
它有一个关键'曲目'
调用is_valid()后,打印的validated_data变为
OrderedDict([('album_name', 'Peter ABC'), ('artist', 'Peter')])
键'跟踪'弹出的类型。
导致save()错误
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
def create(self, validated_data):
print(validated_data)
tracks_data = validated_data.pop('tracks')
album = Album.objects.create(**validated_data)
for track_data in tracks_data:
Track.objects.create(album=album, **track_data)
return album
tracks_data = validated_data.pop('tracks')将失败。 create()内的print(validated_data)也有'track'键突然消失
{'album_name': 'Peter ABC', 'artist': 'Peter'}
我可以知道为什么吗?我的Django 1.11.4版本和Django Rest Framework版本是3.6.3
答案 0 :(得分:1)
tracks = TrackSerializer(many=True)
删除AlbumSerializer中的read_only = True