How to include annotation in JSON string?

流过昼夜 提交于 2019-12-11 17:26:14

问题


I've got a view that returns a list of shipments encoded as JSON...

def get_new_shipments(request):
    # ...
    shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
        .annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount'))
    return json_response(shipments)

def json_response(data):
    response = HttpResponse(mimetype='application/json')
    serializer = serializers.get_serializer("json")()
    data = list(data)
    serializer.serialize(data, ensure_ascii=False, stream=response)
    return response

But I don't see those annotations in the JSON anywhere... how do I get them to be included?


回答1:


This seems to work:

return HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json')

def json_formatter(obj):
    if isinstance(obj, datetime.datetime):
        return obj.isoformat()
    elif isinstance(obj, Decimal):
        return unicode(obj)
    else:
        raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))

credit



来源:https://stackoverflow.com/questions/4035686/how-to-include-annotation-in-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!