我的API上有下一个视图
class CapsuleViewSet(viewsets.ModelViewSet):
queryset = Capsule.objects.all()
serializer_class = CapsuleSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
@action(detail=True)
def modules(self, request, pk=None):
capsule = self.get_object()
capsule_modules = Module.objects.filter(capsule=capsule)
serializer = ModuleSerializer(capsule_modules, many=True)
return Response(serializer.data)
当我尝试获取与胶囊相关的所有模块时,模块的imageField的URL不完整。
当我致电http://0.0.0.0:8000/api/capsules/1/时,它会返回:
{
"capsuleID": 1,
"capsuleName": "sdfads",
"capusuleDetails": "asdf",
"capsuleImageURL": "http://0.0.0.0:8000/media/capsulas/logocitbm.png",
"userStars": 0,
"pallete": {
"palleteID": 1,
"palleteName": "Default smartraining",
"colors": [
{
"colorID": 1,
"colorName": "A1",
"colorCode": "#sdfs"
},
{
"colorID": 2,
"colorName": "A2",
"colorCode": "#dsfksdoif"
},
{
"colorID": 3,
"colorName": "A3",
"colorCode": "#sdjfjgioj"
}
]
}
}
但是当我打电话给http://0.0.0.0:8000/api/capsules/1/modules/时,我得到了:
[
{
"moduleID": 1,
"moduleName": "sdfa",
"moduleDetails": "así",
"moduleImageURL": "/media/modulos/9_-_4._Detalle_C%C3%A1psula.png",
"userScore": 0
}
]
moduleImageURL不完整,为什么? 这些是我的序列化器:
class CapsuleSerializer(serializers.ModelSerializer):
pallete = PalleteSerializer(read_only=True)
class Meta:
model = Capsule
fields = ('capsuleID', 'capsuleName', 'capusuleDetails', 'capsuleImageURL', 'userStars', 'pallete')
class ModuleSerializer(serializers.ModelSerializer):
class Meta:
model = Module
fields = ('moduleID', 'moduleName', 'moduleDetails', 'moduleImageURL', 'userScore')
答案 0 :(得分:1)
经过一些研究后,我发现我需要将上下文传递给ModelSerializer,如下所示:
serializer = ModuleSerializer(capsule_modules, many=True, context={'request': request})