Django Rest Framework文档有一个可写嵌套序列化器的示例,请参阅http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers。
我感兴趣的是除了外键字段之外,相关Track
模型只有一个字段(title
)。我因此将其修改为:
models.py
class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
class Meta:
unique_together = ('album', 'title')
serializers.py
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('title',)
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
def create(self, 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
现在运行:
>>> data = {
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'title': 'Public Service Announcement'},
{'title': 'What More Can I Say'},
{'title': 'Encore'},
],
}
>>> serializer = AlbumSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<Album: Album object>
问题:
我需要将序列化数据中的曲目结构化为曲目标题字符串列表,而不是像{'title': title}
这样的词典列表:
>>> data = {
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
'Public Service Announcement',
'What More Can I Say',
'Encore',
],
}
我尝试调整AlbumSerializers
的{{1}}和to_representation
方法,但无法使其符合序列化程序可写的要求。我错过了什么?
答案 0 :(得分:1)
tracks = serializers.SerializerMethodField()
def get_tracks(self, obj):
return obj.tracks.values_list('title', flat=True)
def create(self, validated_data):
data = self.context['request'].data.copy()
tracks_data = data.get('tracks', [])
album = Album.objects.create(**validated_data)
for track_data in tracks_data:
Track.objects.create(album=album, **track_data)
return album