Python 如何在Django中序列化ImageField?
我正在尝试序列化我的一个模型,它有一个Python 如何在Django中序列化ImageField?,python,django,json,serialization,django-models,Python,Django,Json,Serialization,Django Models,我正在尝试序列化我的一个模型,它有一个ImageField。内置的序列化程序似乎无法序列化,因此我考虑编写一个自定义序列化程序。您能告诉我如何序列化一个图像并将其与Django中的默认JSON序列化程序一起使用吗 谢谢为了序列化要在JSON中使用的图像,您可以尝试我为simplejson编码器编写了一个扩展。它返回图像的路径,而不是将图像序列化为base643。下面是一个片段: def encode_datetime(obj): """ Extended encoder func
ImageField
。内置的序列化程序似乎无法序列化,因此我考虑编写一个自定义序列化程序。您能告诉我如何序列化一个图像并将其与Django中的默认JSON序列化程序一起使用吗
谢谢为了序列化要在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")
无法序列化该对象,因为它是一个映像。必须序列化其路径的字符串表示形式 实现它的最简单方法是在您需要序列化它时调用它的str()方法
json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3
应该可以工作。使用另一个编码器,以便:
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)
谢谢你的解决方案。我必须承认-不序列化
ImageFieldFile
开箱即用相当于。。。Django的荒谬。