0

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'>
>>>
2
  • The docs for statistics.mean say that it accepts a sequence or iterable, are you sure you need to convert the queryset to a list, have you tried passing the queryset to statistics.mean? Also, you could perform this calculation on the database using an aggregation Commented Feb 24, 2022 at 21:03
  • @IainShelvington I never thought of trying that - I will try Commented Feb 24, 2022 at 21:05

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Just what I need.

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.