DRF:在'ImageField'上使用'SlugRelatedField'

时间:2015-10-31 12:14:55

标签: django django-rest-framework

django模型是:

<module>zeppelin-R</module>

序列化器是:

class Post(models.Model):
    name = models.CharField()

class PostImage(models.Model):
    image = models.ImageField()
    post = models.ForeignKey(
        Post,
        related_name=images,
    )

串行器数据输出为:

class PostSerialiser(serializers.ModelSerializer):
    name = serializers.CharField()
    images = serializers.SlugRelatedField(
        slug_field='image',
        many=True,
        read_only=True,
    )

class Meta:
    model = PostModel
    fields = ('name' 'images',)

但是当尝试获取相同数据的 分页响应 时,它会因错误[ { "name": 'Name 1', "images": [ <ImageFieldFile: 1.jpg>, <ImageFieldFile: 2.jpg>, ], }, { "name": 'Name 2', "images": [ <ImageFieldFile: 5.jpg>, ], } ] 而崩溃

由于存在'ascii' codec can't decode byte 0xff in position 23: ordinal not in range(128)"而不是网址。

如何获取图片的 绝对网址 (MEDIA_URL + image-relative-url)而不是ImageFieldFile

2 个答案:

答案 0 :(得分:2)

能够找出to_representation FileField的实施情况。

class ImageUrlField(serializers.RelatedField):
    def to_representation(self, instance):
        url = instance.image.url
        request = self.context.get('request', None)
            if request is not None:
            return request.build_absolute_uri(url)
        return url

class PostSerialiser(serializers.ModelSerializer):
    name = serializers.CharField()
    images = serializers.ImageUrlField(many=True, read_only=True)

答案 1 :(得分:0)

我对ImageFields没有太多经验,所以可能有另一种解决方案,但肯定会有效:

class ImageUrlField(serializers.RelatedField):
    def to_representation(self, value):
        # Build absolute URL (next line is just sample code)
        str = settings.MEDIA_URL + str(value.image) 
        return str

class PostSerialiser(serializers.ModelSerializer):
    name = serializers.CharField()
    images = serializers.ImageUrlField(many=True, read_only=True)