I have the following table in my Django Models:
Date | Field1 | Field2 | Field3 | Field4 | Field5 | Field6 |
05/01/2018 | 7 | 1 | 8 | 4 | 9 | 2 |
05/02/2018 | 9 | 2 | 1 | 1 | 6 | 2 |
05/03/2018 | 8 | 1 | 3 | 1 | 5 | 1 |
05/04/2018 | 7 | 1 | 8 | 4 | 9 | 2 |
05/05/2018 | 7 | 1 | 8 | 4 | 9 | 2 |
I would like to return the names of the top 3 fields with the highest sum over a custom time period.
For example if I want to get the NAMES of the Top 3 fields with the highest sum between 05/02/2018 and 05/04/2018, this should return the following:
'Field1, Field5, Field3'
because:
Date | Field1 | Field2 | Field3 | Field4 | Field5 | Field6 |
05/02/2018 | 9 | 2 | 1 | 1 | 6 | 2 |
05/03/2018 | 8 | 1 | 3 | 1 | 5 | 1 |
05/04/2018 | 7 | 1 | 8 | 4 | 9 | 2 |
SUM | 24 | 4 | 12 | 6 | 20 | 5 |
I could do the following:
1) Return a list of field names (attributes of my Django model's class) using __dict__
2) Loop through all field names, sum up their values in the table by filtering for dates and using .aggregate(SUM()) and put my results into a dictionary of {FieldNames: Sums}
3) And finally sort the dictionary out by values (Sums) and extract the keys (Field Names) corresponding to the top 3 values.
This kind of seems like it would be overkill and I'am wondering if there is a more Pythonic/Django-esque way of achieving this using Querysets?