gpt4 book ai didi

python - 如何在 Django 中序列化 ImageField?

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:37 24 4
gpt4 key购买 nike

我正在尝试序列化我的一个具有 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")

关于python - 如何在 Django 中序列化 ImageField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7497138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com