【问题标题】:How do I serialize an ImageField in Django?如何在 Django 中序列化 ImageField?
【发布时间】:2011-11-21 18:23:32
【问题描述】:

我正在尝试序列化我的一个具有ImageField 的模型。内置的序列化程序似乎无法序列化,因此我想编写一个自定义序列化程序。你能告诉我如何序列化图像并将其与 Django 中的默认 JSON 序列化程序一起使用吗?

谢谢

【问题讨论】:

    标签: python django json serialization django-models


    【解决方案1】:

    我为 simplejson 编码器编写了一个扩展。它不是将图像序列化为 base643,而是返回图像的路径。这是一个sn-p:

    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")
    

    【讨论】:

    • 感谢您的解决方案。我必须承认 - 不序列化 ImageFieldFile 开箱即用相当...... Django 荒谬。
    【解决方案2】:

    你不能序列化对象,因为它是一个图像。您必须序列化其路径的字符串表示形式。

    实现它的最简单方法是在你对它进行序列化时调用它的 str() 方法。

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

    应该可以。

    【讨论】:

    • 如果给出更多上下文,这个答案可能非常有用,特别是对于 Django 新手。例如,该代码应该放在哪里?
    【解决方案3】:

    您可以尝试使用base64 encoding 来序列化要在 JSON 中使用的图像

    【讨论】:

      【解决方案4】:

      使用另一个编码器,这样:

      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)
      

      【讨论】:

        猜你喜欢
        • 2017-03-21
        • 2017-03-30
        • 2016-06-02
        • 2018-09-16
        • 2020-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-15
        相关资源
        最近更新 更多