如何将空ImageField序列化为JsonResponse?

时间:2016-11-16 11:47:05

标签: python json django serialization model

我有一个模特:

class Item(models.Model):
    title = models.TextField(verbose_name='Title', default='Default title')
    photo = models.ImageField(verbose_name='Photo',upload_to='media/',blank=True)

    def __str__(self):
        return self.title

我正在尝试将此模型对象序列化为前端的JSON响应。这是我的测试观点:

from app.models import Item
from django.forms.models import model_to_dict
from django.http import JsonResponse

def get(self, request, *args, **kwargs):
    item_object = Item.objects.first()
    to_json = model_to_dict(item_object)
    return JsonResponse(to_json)

当我创建没有照片字段的Item对象时(来自django shell而没有下载真实文件,这个字段不是必须的),JsonResponse抛出TypeError:不是JSON可序列化的

[16/Nov/2016 13:51:15] "GET /items/?item_id=9&shop_id=4 HTTP/1.1" 500 129160
Internal Server Error: /items/
Traceback (most recent call last):
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/lamberk/python/picasel/rc_cross_upsell/CrossUpsell/apps/items/views.py", line 54, in get
    'up_sells': up_sells,
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/http/response.py", line 520, in __init__
    data = json.dumps(data, cls=encoder, **json_dumps_params)
  File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/serializers/json.py", line 118, in default
    return super(DjangoJSONEncoder, self).default(o)
  File "/usr/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <ImageFieldFile: None> is not JSON serializable

2 个答案:

答案 0 :(得分:0)

您可以编写项目序列化程序并使用它而不是model_to_dict()

http://www.django-rest-framework.org/api-guide/serializers/

或者如果你想使用model_to_dict,你可以把你的代码放在if else块中。

def get(self, request, *args, **kwargs):
    item_object = Item.objects.first()
    if item_object:
        to_json = model_to_dict(item_object)
        return JsonResponse(to_json)

答案 1 :(得分:0)

我建议使用自定义JSON编码器,这些就是这些:

from collections import Counter
a = [1,2,3,2,4,3,1,7,4,3]
counter = Counter(a)
print(a.most_common())

并像这样使用它:

class CustomEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, ImageFieldFile):
            # Do whatever appropriate for your case, like returning None
        return super(LazyEncoder, self).default(obj)