在我的项目中,我想使用Serializer类获取图像的完整路径。
当我使用ViewSet类时,似乎得到正确的结果。但是当使用APIView类时,并不能满足我的需求。
# the model
class UserAccount(models.Model):
...
icon = models.ImageField(upload_to='icon/user')
# the serializer
class UserSerializer(serialziers.ModelSerializer):
class Meta:
model = UserAccount
fields = (..., 'icon')
使用ViewSet
# viewset
class UserViewSet(viewsets.ModelViewSet):
...
serializer_class = UserSerializer
# result
# {..., 'icon': 'http://127.0.0.1:8000/media/icon/user/filename'}
使用APIView
class UserView(APIView):
...
def get(self, request):
...
userAccount = user.userAccount
serializer = UserSerializer(userAccount)
return Response(serializer.data)
# result
# {..., 'icon': '/media/icon/user/filename'}
我应该怎么做才能在APIView中获得图像的完整路径?
答案 0 :(得分:2)
您需要使用SerializerMethodField
添加其他字段:
class UserSerializer(serializers.ModelSerializer):
icon_url = serializers.SerializerMethodField()
class Meta:
model = UserAccount
fields = (..., 'icon_url')
def get_icon_url(self, user_account):
request = self.context.get('request')
icon_url = user_account.icon.url
return request.build_absolute_uri(icon_url)
并将request
添加到视图中的上下文:
def get(self, request):
...
userAccount = user.userAccount
serializer = UserSerializer(userAccount, context={'request':request})
return Response(serializer.data)