문제발생
class ProductSerializer(serializers.ModelSerializer):
brand_id = serializers.PrimaryKeyRelatedField(
queryset=Brand.objects.all(),
write_only=True
)
brand = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Product
fields = [... 'brand']
def get_brand(self, obj):
"""
브랜드 정보
"""
brand = obj.brand_id
print('brand_logo_img : ', brand.logo_img)
if brand:
brand_data = {
'id': brand.id,
'name': brand.name,
'description': brand.description,
'logo_img': brand.logo_img,
'links': brand.links
}
return brand_data
상품 Serializer에서 brand 정보를 가져오려 했더니 'logo_img'에서 에러가 나타났다.
해결방법
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 에러는 일반적으로 이미지 파일을 인코딩할 때 발생하는 문제다. logo_img 필드는 이미지 파일을 저장하는 필드로, 해당 필드의 값을 직접 인코딩하려고 하면 발생할 수 있는 문제였다.
해당 에러를 해결하기 위해선 logo_img 필드 값을 직접 가져오는 대신 해당 필드의 URL을 가져와서 사용하는 방법을 고려할 수 있었다.
해결
...
def get_brand(self, obj):
"""
브랜드 정보
"""
brand = obj.brand_id
print('brand_logo_img : ', brand.logo_img)
if brand:
brand_data = {
'id': brand.id,
'name': brand.name,
'description': brand.description,
'logo_img': brand.logo_img.url,
'links': brand.links
}
return brand_data
'DevOps > TIL' 카테고리의 다른 글
[ERROR] most likely due to a circular import (0) | 2023.06.12 |
---|