I have a number of records that come from database. I want to convert the structure of the DB records to be more like a parent and child class
So forecast_data has properties as follows:
component_plan_id, region, planning_item, cfg, measure, period_str, currency, forecast_value, forecast_currency
The idea is to convert to parent record, with property
component_plan_id, region, planning_item, cfg, measure, currency
and the child record for each parent record will be
period_str, forecast_value, forecast_currency
So what I do in my code, is that
1. Get the list of unique property in parent's records
2. For each record in (1), get records with the same attribute, create child record with period_str, forecast_value, forecast_currency
The code below already works, but somehow it is too slow. Is there any way to enhance the performance?
data = []
# Format the forecast data
for rec in list(set((row.component_plan_id, row.region,
row.planning_item, row.cfg, row.measure, row.currency) for row in forecast_data)):
new_rec = ComponentForecastReadDto(component_plan_id = rec[0],
region = rec[1], planning_item = rec[2],
cfg = rec[3], measure = rec[4], currency = rec[5])
# Get forecast value
new_rec.forecast = []
for rec_forecast in [x for x in forecast_data if
x.component_plan_id == new_rec.component_plan_id and
x.region == new_rec.region and
x.planning_item == new_rec.planning_item and
x.cfg == new_rec.cfg and
x.measure == new_rec.measure and
x.currency == new_rec.currency]:
new_forecast = ComponentForecastValueReadDto(period_str = rec_forecast.period_str,
forecast_value = rec_forecast.forecast_value, forecast_currency = rec_forecast.forecast_currency)
new_rec.forecast.append(new_forecast)
data.append(new_rec)
ComponentForecastReadDto and ComponentForecastValueReadDto are inherited from BaseModel in pydantic.
Sample input:
| component_plan id | region | planning_item | cfg | measure | period_str | currency | forecast_value | forecast_currency |
| 1 | America | Item 1 | cfg A | unit | 2022-06 | 2 | 100 | 200 |
| 1 | America | Item 1 | cfg A | unit | 2022-07 | 2 | 150 | 300 |
| 1 | America | Item 1 | cfg A | unit | 2022-08 | 2 | 200 | 400 |
| 1 | Asia | Item 1 | cfg A | unit | 2022-06 | 3 | 150 | 450 |
Output
Record #1
component_plan_id = 1
region = America
planning_item = Item 1
cfg = cfg A
measure = unit
currency = 2
children:
1. period_str = 2022-06
forecast_value = 100
forecast_currency = 200
2. period_str = 2022-07
forecast_value = 150
forecast_currency = 300
3. period_str = 2022-08
forecast_value = 200
forecast_currency = 400
Record #2
component_plan_id = 1
region = Asia
planning_item = Item 1
cfg = cfg A
measure = unit
currency = 3
children:
1. period_str = 2022-06
forecast_value = 150
forecast_currency = 450