【问题标题】:DRF Image serializer with nested thumnails带有嵌套缩略图的 DRF 图像序列化程序
【发布时间】:2022-07-11 18:29:01
【问题描述】:

我正在编写 django 项目,其中我的 media_app 应用程序中有以下模型:

class Image(File):
    """
    Image model class, through which client will get images stored on AWS S3.
    """
    # ... (not needed in serializer fields)



class Thumbnail(File):
    """
    Related model for Image, that contains thumbnails of Image.
    """
    parent = models.ForeignKey(
        Image,
        on_delete=models.CASCADE,
        related_name='thumbnails',
    )
    resolution = models.CharField(
        _('resolution'),
        max_length=11,
        validators=[resolution_validator],
    )
    
    # ...

文件类是我项目中媒体文件的基本模型类。它包含mime_type, origina_file_name, size等。

我的问题是如何为 Image 编写序列化程序,其结构如下:

{
  "2775f83e-1608-4135-91d3-f357484df3b1": {
    "full_size": "http://localhost:8000/api/media/2775f83e-1608-4135-91d3-f357484df3b1/",
    "358x227": "http://localhost:8000/api/media/8809a43d-c387-4a8e-9c84-8419c406ecd8/",
    "190x121": "http://localhost:8000/api/media/cb32967e-a576-44ee-b636-6e3a65ec93ba/"
  }
}

"2775f...df3b1" 是 Image 的 pk,"full_size" 是它自己的 get url(模型有方法/属性api_url,生成端点 url 到媒体文件获取视图)和其他字段("358x227""190x121" ) 是相关缩略图的 url(键来自缩略图中的分辨率字段)。这种结构对于 DRF 来说并不常见,所以我在文档中没有找到解决方案...

Serializer 将在其他 ModelSerializer 中使用。 Image 包含其他模型的外键,那些需要媒体文件(我没有使用 Django 内容类型,只是可以为空的 OneToOnes),并且在 api_url 中会有用于 Image 的普通 ModelSerializer,所以我只需要像文章这样的相关模型中的上述结构。

【问题讨论】:

    标签: django django-rest-framework response


    【解决方案1】:

    我检查了其他一些stackOverflow问题,找到了ModelSerializer的.to_representation方法。为了获得所需的表示(高于结构),我只是重写了这个方法。结果如下代码:

    
    class RelatedImageSerializer(serializers.ModelSerializer):
        
        def to_representation(self, instance):
            thumbnails = instance.thumbnails.all()
            image_api_urls = {"full_size": instance.api_url}
            for thumbnail in thumbnails:
                image_api_urls[thumbnail.resolution] = thumbnail.api_url
            
            
            return {str(instance.pk): image_api_urls}
        
        class Meta:
            model = Image
            fields = ('id',) # will not be used, because to_representation method was overwrite
    

    一切正常,但我没有检查所有情况,只是我的 API 的 2 个端点。

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多