Python 使用django序列化程序时出现UnicodeDecodeError

Python 使用django序列化程序时出现UnicodeDecodeError,python,django,django-models,django-rest-framework,django-serializer,Python,Django,Django Models,Django Rest Framework,Django Serializer,我有一个自定义django用户模型和一个外键为“CustomUser”模型的“Photo”模型: 及 我试图从Photo Serializer获取“profile_pic”字段(在CustomUser中定义),但我得到了一个utf-8错误。 照片序列化程序: class PhotoSerializer(ModelSerializer): email = serializers.SerializerMethodField('get_user_email') username =

我有一个自定义django用户模型和一个外键为“CustomUser”模型的“Photo”模型:

我试图从Photo Serializer获取“profile_pic”字段(在CustomUser中定义),但我得到了一个utf-8错误。

照片序列化程序:

class PhotoSerializer(ModelSerializer):

    email = serializers.SerializerMethodField('get_user_email')
    username = serializers.SerializerMethodField('get_username')
    profile_pic = serializers.SerializerMethodField('get_profile_pic')
    
    class Meta:
        model = Photo
        fields = ['id', 'author','image', 'title','email', 'username', 'profile_pic']

    def get_user_email(self, photo):
        email = photo.author.email
        return email

    def get_username(self, photo):
        username = photo.author.username
        return username
        
    def get_profile_pic(self, photo):
        photo_url = photo.author.profile_pic  
        return photo_url
如果我用下面的代码替换get_profile_pic,它会给出正确的图像url。但是还有其他的方法吗?我也想知道错误的原因

def get_profile_pic(self, photo):
        request = self.context.get('request')
        photo_url = photo.author.profile_pic  
        photo_url = 'media/' + str(photo_url)
        return request.build_absolute_uri(photo_url)

您的方法
get\u profile\u pic
返回一个
ImageFieldFile
对象,而不是
str

您应该使用
url
属性:

def get_profile_pic(self, photo):
    photo_url = photo.author.profile_pic.url
    return photo_url

请参见您的方法
get\u profile\u pic
返回
ImageFieldFile
对象,而不是
str

您应该使用
url
属性:

def get_profile_pic(self, photo):
    photo_url = photo.author.profile_pic.url
    return photo_url

参见

这不是
照片.作者.个人资料\u图片\u url
?(缺少
\u url
后缀?)?(缺少
\u url
后缀?)
def get_profile_pic(self, photo):
    photo_url = photo.author.profile_pic.url
    return photo_url