Harp Angell
Harp Angell

Reputation: 79

Django objects queryset

I have a question regarding django queries. I have a query like so:

x = Foo.objects.order_by('date').values('amount')

and this returns something like:

[{'amount': Decimal('100.2200')},{'amount': Decimal('100.2200')}....]

What I want to do is get the standard deviation of these decimals but I cannot seem to figure out how to get them from the dictionary to just the decimals in a list. I tried a for statement but that doesn't work and list comprehension returns:

[Decimal('100.2200'), Decimal('100.2300')...]

With this code:

x = Foo.objects.order_by('date').values('amount')
x = ([amount.values()[0] for amount in x])
print x

Am I doing this wrong? Should I be making sql queries to the server if I want to get the info back and manipulate it?

Basically what I want to do is get the standard dev of all the amounts in a certain table based on specific filters...

Thank you so much for your help

Upvotes: 1

Views: 384

Answers (1)

karthikr
karthikr

Reputation: 99620

First, you can get the list of decimals directly by using values_list

qs = Foo.objects.order_by('date').values_list('amount', flat=True)

Secondly, if it is easier to calculate SD on floats, rather than on a list of decimals, you can do

qs = Foo.objects.order_by('date').values_list('amount', flat=True)
float_qs = map(float, qs)

Upvotes: 2

Related Questions