在我的项目中,我想使用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中获得图像的完整路径?
最佳答案
您需要使用SerializerMethodField添加其他字段:
原文链接:https://www.f2er.com/python/533157.htmlclass 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)
并在视图中向上下文添加请求:
def get(self,request):
...
userAccount = user.userAccount
serializer = UserSerializer(userAccount,context={'request':request})
return Response(serializer.data)