django - 如何在 django rest 框架中从另一个模型序列化 ImageField
问题描述
我知道有很多类似的问题,但没有一个能解决我的问题。
我有一个简单的主题,它有一个图像字段、一个主题标题、一个主题内容、一个主题段等。
该主题与使用外键的用户相关联。序列化程序运行良好,直到
添加了图像字段的序列化程序。
序列化程序.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
我不是只存储图像的路径而不是图像本身吗?我的意思是我有一个用户配置文件序列化程序,它向请求的用户发送信息,它包含一个图像。但它工作正常。
解决方案
def get_topic_author_picture(self, topic):
return topic.owner.profile_picture.url
推荐阅读
- android - 使用 ReLinker 加载库时 Android Studio 中的测试出错
- javascript - Angular 在一行上显示数组的四个元素
- javascript - 每次更改 innerHTML 时,如何停止光标移动到开头?
- sql - 表达式中的 Postgresql 子查询返回多于一行
- eclipse - eclipse可以将Java编辑连接到JSF文件,如果可以,如何启用它?
- kivymd - 如何将排序图标的位置更改为 Kivymd 数据表中单元格标题的右侧
- com - 版本化的类似乎是由 REGASM 创建的——如何使用它们?
- google-api - 在 Google Calendar API 中,如何确定日历是 Google 创建的日历还是用户创建的工作空间日历
- angularjs - UI Grid - Expand Row 在底部添加空白区域
- kubernetes - 在运行时将 ConfigMap 的数据部分中的属性替换为 Kubernetes 中的环境变量