Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset to dict for use in json

Tags:

django

I have the following queryset:

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

How can i get the prices as "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"]
]}
like image 539
nelsonvarela Avatar asked May 08 '12 15:05

nelsonvarela


People also ask

How does QuerySet work in Django?

A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters. In SQL terms, a QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT .

What is __ in Django ORM?

Django Field Lookups Managers and QuerySet objects comes with a feature called lookups. A lookup is composed of a model field followed by two underscores ( __ ) which is then followed by lookup name.


1 Answers

A better approach is to use DjangoJSONEncoder. It has support for 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)

Very easy to use. No jumping through hoops for converting individual fields to float.

Update : Changed the answer to use builtin json instead of simplejson.

like image 68
Vashishtha Jogi Avatar answered Sep 21 '22 15:09

Vashishtha Jogi