gpt4 book ai didi

python - 如何修复 Django REST Framework 中的 UnicodeDecodeError?

转载 作者:行者123 更新时间:2023-12-01 06:38:01 24 4
gpt4 key购买 nike

我想在可浏览的 API 中显示 ProductImageSerializer。但我收到了这个错误:

UnicodeDecodeError at /api/product_images/
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Unicode error hint
The string that could not be encoded/decoded was: �����

这是我的models.py:

class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField(upload_to='product_images', width_field=None, height_field=None,
max_length=250)
default = models.BooleanField(verbose_name='Default Picture', default=False)

def __str__(self):
return '%s - %s' % (self.product.product_id, self.default)

这是我的serializers.py:

class ProductImageSerializer(serializers.ModelSerializer):
product = serializers.PrimaryKeyRelatedField(many=False, queryset=Product.objects.all())

class Meta:
model = ProductImage
fields = ['id', 'product', 'image', 'default']

def to_representation(self, instance):
if self.context['request'].method == 'GET':
product = ProductSerializer(instance.product, many=False, context=self.context).data
data = {
'id': instance.id,
'product': product,
'image': instance.image,
'default': instance.default,
}
return data
return Serializer.to_representation(self, instance)

这是我的views.py:

class ProductImageView(viewsets.ModelViewSet):
queryset = ProductImage.objects.all()
serializer_class = ProductImageSerializer

根据我在 StackOverflow 帖子中搜索的内容,我认为问题是由 image 字段引起的。

这是我从 serializers.py 中的 to_representation 函数中删除 image 字段时的屏幕截图:

enter image description here

我应该在 ProductImageSerializer 中添加或编辑什么才能正确显示 image 字段?

最佳答案

尝试

instance.image.url instead of instance.image 

并用于完整网址

self.context['request'].build_absolute_uri(instance.image.url)

阅读完所有代码后,您也可以这样做


class ProductImageSerializer(serializers.ModelSerializer):
product = ProductSerializer()

class Meta:
model = ProductImage
fields = ['id', 'product', 'image', 'default']
# remove to_representation function

您还可以在新的关键“图像”中显示与产品相关的图像

# in your product serializer it will be like this
class ProductImageSerializer(serailizers.ModelSerializer):
class Meta:
model = ProductImage
fields = ['id', 'image', 'default']

class ProductSerializer(serializers.ModelSerilaizer):
images = ProductImageSerializer(many=True)
# should send many = True as it may be more than image related to every product
class Meta:
model = Product
fields = [....., 'images']

您还可以使用 SerializerMethodField 将图像作为字符串列表获取

关于python - 如何修复 Django REST Framework 中的 UnicodeDecodeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59577296/

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