[Answered ]-Django – queryset include element at start of each result row

1👍

Assuming I’ve understood your question well, this is how I would do it:

In [1]: qs_results = [{'trgjob_id': 22659, 'trgmst_id': 'Tidal - Default Email Abnormal', 'jobmst_id': 10081, 'trgjob_order': 1, 'trgjob_type': 0, 'trgjob_level': 0}, 
   ...: {'trgjob_id': 29054, 'trgmst_id': 'CADIS - DMS Email Abnormal ', 'jobmst_id': 10081, 'trgjob_order': 2, 'trgjob_type': 0, 'trgjob_level': 0}, 
   ...: {'trgjob_id': 29055, 'trgmst_id': 'CADIS - DMS Email Error ', 'jobmst_id': 10081, 'trgjob_order': 3, 'trgjob_type': 0, 'trgjob_level': 0}]

In [2]: client_results = [{'trgjob':item} for item in qs_results]

In [3]: client_results
Out[3]: 
[{'trgjob': {'jobmst_id': 10081,
   'trgjob_id': 22659,
   'trgjob_level': 0,
   'trgjob_order': 1,
   'trgjob_type': 0,
   'trgmst_id': 'Tidal - Default Email Abnormal'}},
 {'trgjob': {'jobmst_id': 10081,
   'trgjob_id': 29054,
   'trgjob_level': 0,
   'trgjob_order': 2,
   'trgjob_type': 0,
   'trgmst_id': 'CADIS - DMS Email Abnormal '}},
 {'trgjob': {'jobmst_id': 10081,
   'trgjob_id': 29055,
   'trgjob_level': 0,
   'trgjob_order': 3,
   'trgjob_type': 0,
   'trgmst_id': 'CADIS - DMS Email Error '}}]

The key is in line 2 which adds a key for each dict item in queryset results qs_results.

1👍

keep it lazy:

for item in qs_results:
    yield {'trgjob':item}

Leave a comment