Last active
April 9, 2022 07:26
-
-
Save theyorubayesian/0d1017eee63cca8df46105ff14064f9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
from pprint import pprint | |
from django.db.models.query import QuerySet | |
def parse_annotated_query_set(qs: QuerySet, nest_level: int = 1) -> dict: | |
""" | |
This function parses annotated query sets and returns a nested dictionary. | |
Params: | |
- qs: Django query set to be parsed into nested dict | |
- nest_level: Number of columns on which result set was grouped | |
""" | |
assert len(qs) != 0, "Query set is empty" | |
assert nest_level <= len(qs) - 1, "Incorrect nest_level for Query Set" | |
all_result = defaultdict(dict) | |
for result_set in qs: | |
keynames = list(result_set.keys()[:nest_level]) | |
keys = list(result_set.values()[:nest_level]) | |
result = { | |
k: v for k, v in result_set.items() if k not in keynames | |
} | |
for key in reversed(keys): | |
result = {key: result} | |
all_result[keys[0]].update(result[key]) | |
return all_result | |
if __name__ == "__main__": | |
data = [ | |
{'billstypecategory': 'Airtime', 'statuscategory': 'Unsuccessful', 'transactions_count': 9427, 'transactions_value': '5560789.30'}, | |
{'billstypecategory': 'Airtime', 'statuscategory': 'Unknown Status', 'transactions_count': 2563, 'transactions_value': '1956772.00'}, | |
{'billstypecategory': 'Betting', 'statuscategory': 'Unsuccessful', 'transactions_count': 418, 'transactions_value': '2968787.00'}, | |
{'billstypecategory': 'Betting', 'statuscategory': 'Pending', 'transactions_count': 133, 'transactions_value': '586640.00'}, | |
{'billstypecategory': 'Betting', 'statuscategory': 'Error', 'transactions_count': 23, 'transactions_value': '1144590.00'}, | |
{'billstypecategory': 'Betting', 'statuscategory': 'Unknown Status', 'transactions_count': 3, 'transactions_value': '10000.00'} | |
] | |
data_dict = parse_annotated_query_set(data, nest_level=2) | |
pprint(data_dict) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment