如何序列化Django中的ImageField?

2024-06-16 11:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试序列化我的一个模型,它有一个ImageField。内置序列化程序似乎无法序列化此内容,因此我考虑编写自定义序列化程序。您能告诉我如何序列化一个图像,并将其与Django中的默认JSON序列化器一起使用吗?

谢谢


Tags: django模型图像程序json内容序列化内置
3条回答

我为simplejson编码器编写了一个扩展。它返回图像的路径,而不是将图像序列化为base643。以下是一个片段:

def encode_datetime(obj):
    """
    Extended encoder function that helps to serialize dates and images
    """
    if isinstance(obj, datetime.date):
        try:
            return obj.strftime('%Y-%m-%d')
        except ValueError, e:
            return ''

    if isinstance(obj, ImageFieldFile):
        try:
            return obj.path
        except ValueError, e:
            return ''

    raise TypeError(repr(obj) + " is not JSON serializable")

无法序列化对象,因为它是图像。必须序列化其路径的字符串表示形式。

实现它的最简单方法是在序列化它时调用它的str()方法。

json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3

应该有用。

您可以尝试base64 encoding来序列化要在JSON中使用的图像

相关问题 更多 >