首页 > 解决方案 > 如何在 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

我不是只存储图像的路径而不是图像本身吗?我的意思是我有一个用户配置文件序列化程序,它向请求的用户发送信息,它包含一个图像。但它工作正常。

标签: djangodjango-rest-frameworkimagefield

解决方案


用作FieldFile.url_

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

推荐阅读