Django Rest Framework 的 django-imagekit 缩略图序列化器 + 额外

问题描述

伙计们。 我花了一些时间弄清楚如何将 django-imagekit 与 DRF 一起使用,而无需在模型中定义 ImageSpecField 字段(大量缩略图类型使模型变脏)。

from collections import OrderedDict
from rest_framework import serializers
from imagekit.cachefiles import ImageCacheFile


class ThumbnailField(serializers.ImageField):
    def __init__(self,spec,**kwargs):
        self.spec = spec
        super().__init__(**kwargs)

    def to_representation(self,original_image):
        if not original_image:
            return None

        cached = ImageCacheFile(self.spec(original_image))
        cached.generate()
        return super().to_representation(cached)


class ImageKitField(serializers.ImageField):
    def __init__(self,**kwargs):
        self.specs = kwargs.pop('specs',{})
        self.full = kwargs.pop('full',False)
        super().__init__(**kwargs)

    def to_representation(self,original_image):
        if not original_image:
            return None

        result = OrderedDict()

        for field_name,spec in self.specs.items():
            cached = ImageCacheFile(spec(original_image))
            cached.generate()
            result[field_name] = super().to_representation(cached)

        if self.full:
            result['full'] = super().to_representation(original_image)

        return result

使用

ThumbnailField 只返回图像缩略图 url。您还可以像这样使用 source 和其他 ImageField 参数:

class UserSerializer(serializers.ModelSerializer):
    thumb = ThumbnailField(spec=UserThumbnailSpec,source='image')

结果:

{
    "thumb": "http://example.com/.../thumb.jpg"
}

ImageKitField 是将多个缩略图维度组合在一起的额外字段。 full 是可选标志,包括原始图像到结果字典。

class UserSerializer(serializers.ModelSerializer):
    image = ThumbnailField(specs={
        'small': SmallThumbnailSpec,'large': LargeThumbnailSpec,},full=True)

结果:

{
    "image": {
        "small": "http://example.com/.../small.jpg","large": "http://example.com/.../large.jpg","full": "http://example.com/.../full.jpg",}
}

享受吧!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)