[Django]-Convert queryset to list in Django

2👍

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

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

👤chandu

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

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

👤f43d65

Leave a comment