How to return a query in JSON format with extra values and custom keys?

2

I want to return the result in JSON following this format:

{"cadastros": [
    {"id": 1, "STATUS": true, "pessoas": [], "podeEscrever": true},
    {"id": 2, "STATUS": false, "pessoas": ['Maria', 'Ana'], "podeEscrever": true},
], 'principal': true}

models.py :

class MyModel(models.Model):
    status = models.BooleanField()
    pessoas = models.ManyToManyField(Pessoa, blank=True)
    podeescrever = models.BooleanField()

Note that in the format JSON there is podeEscrever with a capital letter, so the result should respect this format too.

The main idea is to use the simplejson library to manipulate the result and return the JSON in the desired format.

views.py :

def minha_views(request):
    p = Pessoa.objects.values()
    data = simplejson.dumps(p)
    # aqui seria formatado
    return HttpResponse(data, content_type='application/json; charset=utf8')

My difficulty is to format JSON , I can return query results straight to JSON , but I do not know how to manipulate it to add new keys and change the name of field podeescrever to podeEscrever .

Another thing that is happening is that the pessoas field that is ManytoManyField does not return in JSON if it is empty, the correct one was to return with an empty list [] if there are no items.

It does not seem difficult to do this, does anyone know how to solve this problem?

    
asked by anonymous 29.07.2015 / 00:28

2 answers

3

I would use list comprehensions in both cases:

return HttpResponse(json.dumps({
    "principal": True,
    "cadastros":[{
        "id":p.id,
        "STATUS":p.status,
        "podeEscrever":p.podeescrever,
        "pessoas":[unicode(pessoa) for pessoa in p.pessoas.all()],
    } for p in MyModel.objects.all().prefetch_related("pessoas")],
}), content_type='application/json; charset=utf8')

This solution can be a little painful if the models are large, but it has the advantage of allowing both the names of the attributes to appear, which ones appear and which do not, and also their format (it is very common for me to format dates, for example , in non-standard form when generating JSON).

Notes: 1) I usually use json and not simplejson , I do not know if it makes a difference; 2) Note the use of prefetch_related to reduce the number of queries to the minimum required.

    
30.07.2015 / 02:03
2

I was able to resolve it as follows:

pessoas = Pessoa.objects.values()
pessoas_modificado = []

for p in pessoas:

    # altera o nome das chaves:
    p['STATUS'] = p.pop('status')
    p['podeEscrever'] = p.pop('podeescrever')

    # retorna lista vazia caso não exista pessoas
    p['pessoas'] = p.get('pessoas', [])

    # adiciona o dicionario a nova lista:
    pessoas_modificado.append(p)

# cria a formatação esperada
dicionario = {'cadastros': list(pessoas_modificado), 'principal': True}

# retorna em JSON
return HttpResponse(simplejson.dumps(dicionario), content_type='application/json; charset=utf8')
    
29.07.2015 / 01:36