简体   繁体   English

如何在 Django 中序列化 ImageField?

[英]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.

相关问题 如何在python django中将Filefield或Imagefield数据序列化为json数据 - How to serialize Filefield or Imagefield data into json data in python django 如何将空 ImageField 序列化为 JsonResponse? - How to serialize empty ImageField to JsonResponse? 如何在 Django 中不将数据放入 ImageField 中? - How can I not put data in ImageField in Django? Django 不更新 ImageField - Django do not update ImageField 如何在 django 中按文件名过滤图像字段 - How can I filter the imagefield by filename in django 如何获取 Django ImageField 的 url? - How can I get the url of a Django ImageField? 如何将来自html5画布的base64图像保存为Django中的ImageField? - How do I save base64 image from html5 canvas as ImageField in Django? 使用python shell,如何将图像与类中的ImageField关联起来(Django) - Using python shell, how do I associate an image with an ImageField in a class (Django) 如何将图像添加到静态文件夹中存在的 django 模型中的图像字段? - How do I add an image to the imagefield in django model that is present in the static folder? 如何将本地存储的图像分配给ImageField字段并在Django中返回其URL? - How do I assign images stored locally to an ImageField field and return its URL in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM