3

I have a queryset with objects having fields date and value.

I need to populate the template with an array [[date_1, value_1],[date_2,value_2],...,[date_n,value_n]].

How is this possible when each object has multiple fields?

I have tried

MyModel.objects.values_list('date', 'value')

but date is printed in datetime format (e.g. datetime.date(2013, 9, 21)) and value is printed as decimal (e.g. Decimal('72495.0')). I need it in a flot.js chart.

Tony Abou-Assaleh
  • 3,000
  • 2
  • 25
  • 37
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

3 Answers3

2
MyModel.objects.values_list('date', 'value', flat=True)

how-to-convert-a-django-queryset-to-a-list

Community
  • 1
  • 1
chandu
  • 1,053
  • 9
  • 18
1

You can use list comprehension:

[(str(my_record.date), str(my_record.value)) for my_record in MyModel.objects.all()]

In fact, this way you can transform the data however you wish.

Wtower
  • 18,848
  • 11
  • 103
  • 80
0
import calendar
import json

raw_data = MyModel.objects.values_list('date', 'value')

result = []
for date, value in raw_data:
    result.append([calendar.timegm(date.timetuple()) * 1000,
                   float(value)])

To use result in template, serialize it to JSON first and pass data to template

data = json.dumps(result)

In template

var data = {{ data|safe }};

Also:

How to convert datetime to timestamp

How to serialize Decimal to JSON

Community
  • 1
  • 1
f43d65
  • 2,264
  • 11
  • 15