[英]How do I serialize an ImageField in Django?
I'm trying to serialize one of my models which has an ImageField
.我正在尝试序列化我的一个具有
ImageField
模型。 The inbuilt serializer can't seem to serialize this and therefore I thought of writing a custom serializer.内置的序列化程序似乎无法序列化它,因此我想编写一个自定义序列化程序。 Could you tell me how I could serialize an image and use this with the default JSON serializer in Django?
您能告诉我如何序列化图像并将其与 Django 中的默认 JSON 序列化程序一起使用吗?
Thanks谢谢
you can't serialize the object, because it's an Image.你不能序列化对象,因为它是一个图像。 You have to serialize the string representation of it's path.
您必须序列化其路径的字符串表示形式。
The easiest way of achiving it is to call it's str() method when you what to serialize it.实现它的最简单方法是在序列化它时调用它的 str() 方法。
json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3
should work.应该管用。
I wrote an extension to the simplejson encoder.我为 simplejson 编码器写了一个扩展。 Instead to serializing the image to base643, it returns the path of the image.
它不是将图像序列化为 base643,而是返回图像的路径。 Here's a snippet:
这是一个片段:
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")
您可以尝试使用base64 编码来序列化要在 JSON 中使用的图像
Use another encoder such that:使用另一个编码器,使得:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.