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.
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With