Django将字典值加载到JSON中

时间:2015-04-28 18:40:46

标签: python json django dictionary

我正在尝试从字典中获取值,并将它们加载到JSON中。我想我几乎已经用波纹管代码了,但它只输出第一组值,我如何循环它以便它将所有的集合放出?

def storeliqour_view(request, store_id):
    objectdicts = {}
    objects = StoreLiquor.objects.filter(storeID=store_id)
    for i in range(len(objects)):
        objectdicts = model_to_dict(objects[i])
        objectdicts["storename"] = objects[i].storeID.StoreName
    data = [objectdicts.values()] 

    #define response
    response = {
        'aaData': data,
        'iTotalRecords': iTotalRecords,
        'iTotalDisplayRecords': iTotalDisplayRecords,
        'sEcho': request.GET['sEcho']
    }

    #serialize to json
    s = BytesIO()
    json.dump(response, s, cls=MainEncoder)
    s.seek(0)
    return HttpResponse(s.read())

现在它输出了这个。如你所见,它只有一套:  {"aaData": [[1, 0.0, 18, 96.6, 7032, false, 2610, "test store"]]}

如何让它输出多个,像这样?: {"aaData": [[1, 0.0, 18, 96.6, 7032, false, 2610, "test store"], [2, 0.0, 18, 96.6, 7032, true, 2610, "test store"]]}

2 个答案:

答案 0 :(得分:1)

您可以使用:

data = [
    model_to_dict(object).values() + [object.storeID.StoreName]
    for object in objects
]

如果只有字典以相同的顺序返回值,这将有效。因此,执行以下操作会更安全:

data = []
if objects:
    keys = model_to_dict(objects[0]).keys()
    for object in objects:
        d = model_to_dict(object)
        data.append([d[key] for key in keys] + [object.storeID.StoreName])

答案 1 :(得分:1)

def storeliqour_view(request, store_id):
    objectdicts = {}
    objects = StoreLiquor.objects.filter(storeID=store_id)
    data = list()
    for i in range(len(objects)):
        objectdicts = model_to_dict(objects[i])
        objectdicts["storename"] = objects[i].storeID.StoreName
        data.append([objectdicts.values()]) 
    # rest of the code here...