我在Django Rest Framework中有一个嵌套的序列化器:
class AlbumSerializer(serializers.Serializer):
title = serializers.CharField()
tracks = TrackSerializer(many=True)
def update(self, instance, validated_data):
instance.title = validated_data.get(
'title', instance.title)
instance.save()
return instance
当我得到东西时,我会看到:
{
"title": "some title",
"tracks": [
{
"name": "some track"
}
]
}
当我使用update时,我取回更新的专辑,减去曲目-我想在201响应中查看曲目。 注意:我不希望嵌套项目可写,我只想能够更新父项并在响应中看到现有的嵌套项目。
更新:
这是我的看法。 注意::每个用户只有一张相册,因此我的某些查看代码会检查用户是否存在,并相应地创建或更新:
class AlbumView(APIView):
serializer_class = AlbumSerializer
def get_object(self, user):
try:
return Album.objects.get(user=user)
except Album.DoesNotExist:
return False
def get(self, request, format=None):
req = self.get_object(user=request.user)
if req:
serializer = AlbumSerializer(req)
return Response(serializer.data)
return Response("No album found")
def post(self, request, format=None):
req = self.get_object(user=request.user)
serializer = AlbumSerializer(data=request.data)
if serializer.is_valid(raise_exception=ValueError):
if req:
serializer.update(instance=req, validated_data=request.data)
else:
serializer.create(user=request.user, validated_data=request.data)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)