2012-05-08 10 views
11

Ho il seguente set di query:Django Queryset per dict per l'uso in JSON

prices = Price.objects.filter(product=product).values_list('price', 'valid_from') 

Come posso ottenere i prezzi come "JSON"

{"aaData": [ 
    ["70.1700", "2007-01-01"], # price, valid_form 
    ["72.6500", "2008-01-01"], # price, valid_form 
    ["74.5500", "2009-01-01"], # price, valid_form 
    ["76.6500", "2010-01-01"] 
]} 

risposta

0
from django.utils import simplejson 

prices = Price.objects.filter(product=product).values_list('price', 'valid_from') 
simplejson.dumps({'aaData': prices}) 

Modifica

Non è chiaro dalla tua domanda che price è un DecimalField. Sembra che tu avresti bisogno di convertire da Decimal a float:

simplejson.dumps({'aaData': (float(price), valid_from) for price, valid_from in prices}) 

In alternativa, se si desidera che il prezzo per essere una stringa:

simplejson.dumps({'aaData': (str(price), valid_from) for price, valid_from in prices}) 
+0

Errore: decimale ('70 .1700 ') non serializzabile JSON – nelsonvarela

+0

Vedere le nuove modifiche nella risposta. – dgel

34

Un approccio migliore è quello di utilizzare DjangoJSONEncoder. Ha il supporto per Decimal.

import json 
from django.core.serializers.json import DjangoJSONEncoder 

prices = Price.objects.filter(product=product).values_list('price', 'valid_from') 

prices_json = json.dumps(list(prices), cls=DjangoJSONEncoder) 

Molto facile da usare. Nessun salto attraverso i cerchi per convertire singoli campi in float.

Aggiornamento: Modificata la risposta per utilizzare json incorporato anziché simplejson.

+5

Solo una nota ... l'uso di 'django.utils.simplejson' è stato sottratto a Django 1.5. Vedi le [note sulla versione] (https://docs.djangoproject.com/en/dev/releases/1.5/#system-version-of-simplejson-no-longer-used) per maggiori informazioni. – Ngenator

+2

seguendo l'esempio mostrato: una volta che ho 'prices_json' come faccio a passare al modello/js? e come accedo da lì? – Maor

Problemi correlati