在我的项目中,我想使用序列化程序类获取图像的完整路径。
当我使用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
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添加附加字段:

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)

关于python - 在Django Rest Framework序列化器中,如何获取图像的完整路径?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54827145/

10-10 22:21