Returning get_status_display in json (Django)

Asked

Viewed 56 times

0

I created an issue.

https://github.com/rg3915/orcamentos/issues/53

I made a chart using Morris JS

https://github.com/rg3915/orcamentos/blob/master/img/graphic.png

inserir a descrição da imagem aqui

Question: how do I return get_status_display in json?

import json
from django.db.models import Count
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from .models import Proposal


def proposal_per_status_json(request):
    ''' Quantidade de orçamentos por status '''
    data = Proposal.objects.values('status')\
        .annotate(value=Count('status'))\
        .order_by('status').values('status', 'value')
    '''
    Precisa reescrever o dicionário com os campos do gráfico,
    que são: 'label' e 'value'.
    '''
    data = [{'label': x['status'], 'value':x['value']} for x in data]
    s = json.dumps(list(data), cls=DjangoJSONEncoder)
    return HttpResponse(s)

http://localhost:8000/Proposal/Proposal/proposal_per_status_json/

[{"label": "a", "value": 11}, {"label": "c", "value": 9}, {"label": "co", "value": 28}, {"label": "elab", "value": 9}, {"label": "p", "value": 14}]

But I wanted to

[{"label": "aprovado", "value": 11}, {"label": "cancelado", "value": 9}, {"label": "concluído", "value": 28}, {"label": "em elaboração", "value": 9}, {"label": "pendente", "value": 14}]

STATUS_FILTER = (
    ('c', 'cancelado'),
    ('elab', 'em elaboração'),
    ('p', 'pendente'),
    ('co', 'concluido'),
    ('a', 'aprovado')
)
  • What you want is not a valid JSON. Jsons are basically Javascript objects, and what you posted are two values, a list and a tuple. You can convert this into a Dict, but it’s not ideal to include data that repeats in AJAX requests because of overhead. I suggest including the status in the template rendering.

1 answer

0


from orcamentos.utils.lists import STATUS_LIST
p=Proposal.objects.values('status')\
.annotate(value=Count('status'))\
.order_by('status').values('status', 'value')
lista=[]
for item in p:
    for choice in STATUS_LIST:
        if choice[0] == item['status']:
            lista.append({'label': choice[1], 'value': item['value']})

return lista
  • Another slightly more performative solution lista = [{'label': STATUS_DICT[item['status']], 'value': item['value']} for item in data].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.