【发布时间】: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