Skip to content
Advertisement

Extracting data from Django Queryset and inserting into a Python list

I am trying to get one column of data from a Django model into a python list for further processing the in Django view.

I have successfully created a simple Django model and populated the data. The fields are: “id”, “x_coord”, “y_coord”. I have run a few commands to extract data from the model. I want to get the values from the “x_coord” field into a Python list so I can then apply the statistics.mean method to all the values. I have had some success in extracting data, see below the Django commands I have issued in the shell, but I can’t get the data into a Python list. Any assistance will be appreciated.

Model definition

#
class CC_pts_to_avg(models.Model):
    x_coord = models.DecimalField(max_digits=3, decimal_places=2)
    y_coord = models.DecimalField(max_digits=3, decimal_places=2)
#
    def __str__(self):
        return self.x_coord

Commands issued in shell

set environment
(in mysite directory) python manage.py shell

from polls.models import CC_pts_to_avg
 
temp_list = CC_pts_to_avg.objects.values_list('x_coord',flat=True)

>>> temp_list
<QuerySet [Decimal('0.60'), Decimal('0.60'), Decimal('0.45'), Decimal('0.60'), Decimal('0.90'), Decimal('0.60'), Decimal('0.60'), Decimal('0.50'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.65'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.50'), Decimal('0.75'), '...(remaining elements truncated)...']>
>>>

>>> temp_list[0]
Decimal('0.60')

>>> temp_list[2]
Decimal('0.45')

>>> type(temp_list[0])
<class 'decimal.Decimal'>

>>> type(temp_list)
<class 'django.db.models.query.QuerySet'>
>>>

Advertisement

Answer

The values_list method returns a ValuesListQuerySet.

to have list change your code as follows

temp_list = list(CC_pts_to_avg.objects.values_list('x_coord',flat=True))
Advertisement