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"]
]}
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With