我正在尝试序列化一个有ImageField
的模型。内置的序列化程序似乎无法将其序列化,因此我想到编写自定义序列化程序。你能告诉我如何序列化图像并将其与Django中的默认JSON序列化器一起使用吗?
由于
答案 0 :(得分:5)
我写了一个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")
答案 1 :(得分:3)
您无法序列化对象,因为它是一个图像。你必须序列化它的路径的字符串表示。
获取它的最简单方法是在序列化它时调用它的str()方法。
json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3
应该有用。
答案 2 :(得分:2)
您可以尝试使用base64 encoding来序列化要在JSON中使用的图像
答案 3 :(得分:0)
使用其他编码器,例如:
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.fields.files import ImageFieldFile
class ExtendedEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, ImageFieldFile):
return str(o)
else:
return super().default(o)
result = json.dumps(your_object, cls=ExtendedEncoder)