Search code examples
djangodjango-rest-frameworkeasy-thumbnails

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.


Solution

  • 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')