gpt4 book ai didi

django - DRF : Using 'SlugRelatedField' on the 'ImageField'

转载 作者:行者123 更新时间:2023-12-05 02:21:36 24 4
gpt4 key购买 nike

django 模型是:

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 : 序号不在范围内 (128)”

这是因为存在 ImageFieldFile 而不是 URL。

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

最佳答案

能够找出对 FileFieldto_representation 实现的调查。

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)

关于django - DRF : Using 'SlugRelatedField' on the 'ImageField' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com