我在模型中使用了models.FileField(),并为它创建了一个简单的ModelSerializer和CreateAPIView。当我使用亚马逊网络服务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的。
希望这是有意义的。
让我知道如果有人有任何想法,因为我只能找到提供完整/绝对路径的解决方案。
谢谢
发布于 2020-10-05 10:32:44
我认为您正在寻找的是序列化方法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这将使序列化程序返回除文件基名之外的所有正常值!
https://stackoverflow.com/questions/64200709
复制相似问题