1

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

1 Answer 1

2

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

5 Comments

You can also get SD directly from DB (SQLite requires an extension module for that, other DBs support it out of the box): Foo.objects.all().aggregate(StdDev('amount')) - docs
@karthikr your first idea still prints out [Decimal('100.2200'), Decimal('100.2300')...]
@rafalmp does it matter if I'm using postgres? I'm running my program on C9 and cant update the python to run 3.
Thanks @karthikr second one is what I need I believe.
@HarpAngell Postgres supports StdDev since at least version 8.1 so I think there will be no problem.

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.