【问题标题】:In django serializer response, how to get rid of absolute path (media_url prefix) for FileField?在 django 序列化程序响应中,如何摆脱 FileField 的绝对路径(media_url 前缀)?
【发布时间】:2020-10-04 23:06:11
【问题描述】:

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

{
    "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。

希望它有意义。

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

谢谢

【问题讨论】:

    标签: django django-rest-framework django-views django-serializer


    【解决方案1】:

    我认为您正在寻找的是序列化方法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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-09
      • 2010-11-15
      • 1970-01-01
      • 2017-05-29
      • 2021-05-05
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多