开发者

How do I serialize an ImageField in Django?

开发者 https://www.devze.com 2023-04-06 21:23 出处:网络
I\'m trying to serialize one of my modelswhich has an 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 c

I'm trying to serialize one of my models which has an 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 th开发者_运维问答is with the default JSON serializer in Django?

Thanks


I wrote an extension to the simplejson encoder. Instead to serializing the image to base643, it returns the path of the image. 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")


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.

json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3

should work.


You could try the base64 encoding in order to serialize the image to be used inside a 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消