我有一个名为“Post”的模型,例如:
# models.py
from django.db import models
from easy_thumbnails.fields import ThumbnailerImageField
class Post(models.Model):
name = models.CharField(max_length=255)
cover = ThumbnailerImageField(upload_to='posts')
然后我有一个模型的序列化器:
# serializers.py
class PostSerializer(serializers.ModelSerializer):
cover = ThumbnailSerializer(alias='small')
class Meta:
model = Post
fields = ['id', 'name', 'cover']
使用缩略图序列化程序:
from rest_framework import serializers
from easy_thumbnails.templatetags.thumbnail import thumbnail_url
class ThumbnailSerializer(serializers.ImageField):
""" Serializer for thumbnail creation using easy-thumbnails (Needed when using Django Rest Framework) """
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
最后我有一个看法:
# views.py
class PostView(generics.RetrieveAPIView):
queryset = Post.objects.filter(enabled=True)
serializer_class = PostSerializer
现在在我的测试中,我尝试创建一个帖子并获取数据(我使用 PyTest):
# tests.py
def test_post_endpoint(client):
post = Post.objects.create(
name="Post 1",
cover="posts/test_image.jpg",
)
response = client.get('/posts/')
assert response.status_code == 200
print(response.data['cover'])
# This prints: http://testserver/posts/
# Instead of: http://testserver/posts/test_image.small.jpg
我也尝试过使用:
cover=SimpleUploadedFile(
name='test_image.jpg',
content=open(image_path, 'rb').read(),
content_type='image/jpeg'
)
但这最终将图像上传到了我不想要的 S3,因为它只是一个测试,它不应该将任何内容上传到云端。
如何获得封面数据的正确响应?像这样的东西:
'http://testserver/posts/test_image.small.jpg'