Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework with easy-thumbnails

With a normal ImageField, serializing the URL is simply image = serializers.ImageField(). What should it look like when using easy-thumbnails?

So far, I've only found a function for getting the URL: Django easy_thumbnails accessing image URLs Using this in a serializer would require a SerializerMethodField, which is an unsatisfying solution. I'm looking for a solution that's as efficient/performant as practical, and on one line.

like image 358
davidtgq Avatar asked Mar 07 '16 01:03

davidtgq


2 Answers

Best solution is probably to subclass serializers.ImageField() and use the the code you found in the to_representation method (docs for custom fields). Your field could then look like this:

from easy_thumbnails.templatetags.thumbnail import thumbnail_url

class ThumbnailSerializer(serializers.ImageField):

    def to_representation(self, instance):
        return thumbnail_url(instance, 'small')
like image 145
ilse2005 Avatar answered Oct 06 '22 20:10

ilse2005


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

using

from api.serializers import ThumbnailSerializer


class ProfileSerializer(serializers.ModelSerializer):
    image = ThumbnailSerializer(alias='image')
    avatar = ThumbnailSerializer(alias='avatar', source='image')
like image 38
Сергей Пустовит Avatar answered Oct 06 '22 21:10

Сергей Пустовит