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.

1

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.