带有简易缩略图的 Django Rest Framework

Django Rest Framework with easy-thumbnails

对于普通的 ImageField,序列化 URL 只是 image = serializers.ImageField()。使用 easy-thumbnails 时应该是什么样子?

到目前为止,我只找到了一个获取 URL 的函数:Django easy_thumbnails accessing image URLs 在序列化器中使用它需要一个 SerializerMethodField,这是一个不令人满意的解决方案。我正在寻找一种与 efficient/performant 一样实用且在线的解决方案。

最好的解决方案可能是继承 serializers.ImageField() 并使用您在 to_representation 方法 (docs for custom fields) 中找到的代码。您的字段可能如下所示:

from easy_thumbnails.templatetags.thumbnail import thumbnail_url

class ThumbnailSerializer(serializers.ImageField):

    def to_representation(self, instance):
        return thumbnail_url(instance, 'small')

你能做的就是。 步骤 1. 安装 sorl-thumbnail 并将其添加到 settings.py

pip install sorl-thumbnail 
./manage.py migrate

步骤 2. 安装 sorl-thumbnail-serializer-field

pip install sorl-thumbnail-serializer-field

将其添加到 settings.py。文档中所述的示例用法 (https://github.com/dessibelle/sorl-thumbnail-serializer-field)

class TestModelSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = TestModel

    # A thumbnail image, sorl options and read-only
    thumbnail = HyperlinkedSorlImageField(
        '128x128',
        options={"crop": "center"},
        source='image',
        read_only=True
    )

    # A larger version of the image, allows writing
    image = HyperlinkedSorlImageField('1024')

Django 3.0 兼容性尚未针对 sorl-thumbnail 进行更新。所以在目前 django 3.0 的情况下。

pip install -e git+git://github.com/jazzband/sorl-thumbnail@4fe1854#egg=sorl-thumbnail 

settings.py

THUMBNAIL_ALIASES = {
    '': {
        'avatar': {'size': (40, 40)},
        'image': {'size': (128, 128)},
    },
}

api/serializers.py

from easy_thumbnails.templatetags.thumbnail import thumbnail_url


class ThumbnailSerializer(serializers.ImageField):
    def __init__(self, alias, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.read_only = True
        self.alias = alias

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

        url = thumbnail_url(value, self.alias)
        request = self.context.get('request', None)
        if request is not None:
            return request.build_absolute_uri(url)
        return url

使用

from api.serializers import ThumbnailSerializer


class ProfileSerializer(serializers.ModelSerializer):
    image = ThumbnailSerializer(alias='image')
    avatar = ThumbnailSerializer(alias='avatar', source='image')

序列化简单缩略图字段的简单包:https://github.com/yashas123/easy-thumbnails-rest