问题
The docs on their GitHub page suggests that what I'm trying to do should work:
thumb_url = profile.photo['avatar'].url
In my project, it gives an error:
THUMBNAIL_ALIASES = {
'': {
'thumb': {'size': (64, 64), 'upscale': False},
},
}
class Image(models.Model):
place = models.ForeignKey(Place, models.CASCADE, 'images')
image = ThumbnailerImageField(upload_to='')
class ImageSerializer(serializers.Serializer):
image = serializers.ImageField()
thumb = serializers.ImageField(source='image.image["thumb"].url')
AttributeError: Got AttributeError when attempting to get a value for field `thumb` on serializer `ImageSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Image` instance.
Original exception text was: 'ThumbnailerImageFieldFile' object has no attribute 'image["thumb"]'.
The url of image
is serialized properly if thumb
is removed. How can I get DRF to serialize the url of the thumbnail?
回答1:
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')
来源:https://stackoverflow.com/questions/35162196/django-easy-thumbnails-serialize-with-django-rest-framework