使用sorl的ImageField的django序列化缩略图

时间:2018-04-06 15:37:56

标签: django amazon-s3 serializer sorl-thumbnail

我有一个现有的序列化程序,其中包含一个ImageField,它可以是非常大的图像。我想要一个较小的缩略图版本的图像。 我正在尝试使用sorl来创建缩略图,因为它能够将其上传到AWS S3。如何在序列化程序中创建此缩略图?

在我当前的serializers.py中:

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ("id", 
                    "username", 
                    "first_name",
                    "last_name",
                    "face_image",)

我的模型看起来像这样,它上传到AWS S3:

class Employee(models.Model):
    username = models.CharField(max_length=30, blank=False)
    first_name = models.CharField(max_length=30, blank=False)
    last_name = models.CharField(max_length=30, blank=False)   
    face_image = models.ImageField(upload_to=upload_to('employee/face_image/'), blank=True, null=True, storage=MediaStorage())

这是尝试在序列化程序中创建一个名为“face_image_small”的新字段,但它不起作用

  from sorl.thumbnail import get_thumbnail
  class EmployeeSerializer(serializers.ModelSerializer):
        class Meta:
            model = Employee
            fields = ("id", 
                        "username", 
                        "first_name",
                        "last_name",
                        "face_image",
                        "face_image_small",)

        face_image_small = get_thumbnail(self.face_image, '200x200', crop='center', quality=99)

1 个答案:

答案 0 :(得分:0)

这是我对此的解决方法:

  from sorl.thumbnail import get_thumbnail
  class EmployeeSerializer(serializers.ModelSerializer):
        class Meta:
            model = Employee
            fields = ("id", 
                        "username", 
                        "first_name",
                        "last_name",
                        "face_image",
                        "face_image_small",)

    face_image_small = serializers.SerializerMethodField()

    def get_face_image_small(self, obj):

        return face_image_small = get_thumbnail(self.face_image, '200x200', crop='center', quality=99).url