如何从Django Rest框架中的另一个模型序列化ImageField

问题描述

我知道有很多类似的问题,但是没有一个解决我的问题。

我有一个简单的主题,其中包含一个图像字段,一个主题标题一个主题内容一个主题标签等。

主题与使用外键的用户相关联。直到

为图像字段添加了序列化器。

serializers.py

class TopicDetailSerializer(serializers.ModelSerializer):
    topic_author = serializers.SerializerMethodField('get_topic_author')
    topic_author_picture = serializers.SerializerMethodField(
        'get_topic_author_picture')

    class Meta:
        model = Topic
        fields = ['id','topic_title','topic_content','created_date','topic_slug','thread_title','topic_author','topic_author_picture',]

    def get_topic_author_picture(self,topic):
        return topic.owner.profile_picture

    def get_topic_author(self,topic):
        return topic.owner.username

当我从前端请求数据时,控制台中的输出

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

我不只是存储图像的路径,而不是图像本身吗?我的意思是我有一个用户配置文件序列化程序,该序列化程序将信息发送给所请求的用户,并且其中包含一个图像。但是效果很好。

解决方法

使用FieldFile.url作为

def get_topic_author_picture(self,topic):
    return topic.owner.profile_picture.url

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...