Skip to main content
 首页 » 编程设计

python之如何在 Django 中序列化 ImageField

2025年05月04日36虾米哥

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

谢谢

请您参考如下方法:

我为 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")