views:

171

answers:

0

I am attempting to create a semi-dynamic aggregate function that will return the sums of all fields within a list. The assumption is that running get_query_set() will return a filtered query that contains all the fields in the list and some others that may not play so well with a Sum aggregate (date fields, char fields, Foreign Keys, etc...)

Best examples I've come up with so far are below, this is largely a python question with Django specific usage though my Python-Fu is not the strongest yet...

Works

qs = cl.get_query_set().aggregate(Sum('permits_submitted'), Sum('permits_pulled'), Sum('permits_posted'))

return: {'permits_pulled__sum': 5772, 'permits_posted__sum': 6723, 'permits_submitted__sum': 7276}

Does not work

qs = cl.get_query_set().aggregate(Sum('permits_submitted')).aggregate(Sum('permits_pulled'))

return: error

qs = cl.get_query_set().aggregate(Sum('permits_submitted', 'permits_pulled', Sum('permits_posted'))

return: error

Does not work - presents the idea

tuple = (
        'permits_submitted',
        'permits_pulled',
        'permits_posted',
    )

qs = cl.get_query_set()
for field in tuple:
    qs.aggregate(Sum(field))

return: error

qs = cl.get_query_set()
qs.aggregate(*[Sum(field) for field in tuple])

return:

[<permit_runner: User's report for 2010-02-18>, <permit_runner: User's report for 2010-02-19>, '...(remaining elements truncated)...'] 

(this is the same as the return without aggregation)

WORKS

qs = cl.get_query_set()
qs = qs.aggregate(*[Sum(field) for field in tuple])

had missed defining qs = when adding the aggregation - helps to take a break for a few minutes and look fresh