在 Django 序列化程序响应中,如何摆脱 FileField 的绝对路径(media_url 前缀)?

In django serializer response, how to get rid of absolute path (media_url prefix) for FileField?

我在模型中使用了 models.FileField() 并为其创建了一个简单的 ModelSerializer 和 CreateAPIView。当我使用 AWS S3 时,在发布文件时,我收到 Json 响应,其中包含 MEDIA_URL 作为文件名的前缀,即:

{
    "id": 32,
    "file": "https://bucket.digitaloceanspaces.com/products/capture_a50407758a6e.png"
}

我想实现的是只保留一个文件名:

{
    "id": 32,
    "file": "capture_a50407758a6e.png"
}

或者能够将前缀更改为其他前缀:

{
    "id": 32,
    "file": "https://google.com/capture_a50407758a6e.png"
}

更改应仅在 Json 响应和数据库条目中可见。 S3 详细信息仍应来源于 settings.py.

希望它有意义。

如果有人有任何想法请告诉我,因为我只能找到提供 full/absolute 路径的解决方案。

谢谢

我认为您正在寻找的是序列化程序方法 to_representation

在你的情况下,这可能看起来像:

import os

class MySerializer(serializers.ModelSerializer):
    # serializer contents

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['file'] = os.path.basename(ret['file'])

        return ret

这应该使序列化程序 return 除了文件的基本名称之外的所有正常值!