@@ -252,7 +252,7 @@ def create_nested_pipeline(model: Type[BaseModel], prefix=""):
252
252
return pipeline , match_conditions
253
253
254
254
255
- def create_model_instance (model : Type [BaseModel ], data : dict ):
255
+ def create_model_instance (model : Type [BaseModel ], data : dict , target_unit : Optional [ str ] = None ):
256
256
nested_fields = get_nested_fields (model )
257
257
258
258
for field_name , _ in model .__fields__ .items ():
@@ -272,7 +272,10 @@ def create_model_instance(model: Type[BaseModel], data: dict):
272
272
if unit_field in data :
273
273
data [field_name ] = data [unit_field ]
274
274
continue
275
- # Check if the mongo_field exists in the data
275
+
276
+ # Handle temperature unit conversion if applicable
277
+ if field_name == "temp" and target_unit and mongo_field in data :
278
+ data [field_name ] = convert_temperature (data [mongo_field ], data .get ("unit" ), target_unit )
276
279
elif mongo_field in data :
277
280
data [field_name ] = data [mongo_field ]
278
281
elif field_name in data :
@@ -293,10 +296,13 @@ def create_model_instance(model: Type[BaseModel], data: dict):
293
296
if field_name in data :
294
297
if isinstance (data [field_name ], list ):
295
298
data [field_name ] = [
296
- create_model_instance (nested_model , item ) for item in data [field_name ]
299
+ create_model_instance (nested_model , item , target_unit )
300
+ for item in data [field_name ]
297
301
]
298
302
else :
299
- data [field_name ] = create_model_instance (nested_model , data [field_name ])
303
+ data [field_name ] = create_model_instance (
304
+ nested_model , data [field_name ], target_unit
305
+ )
300
306
301
307
logger .debug (f"Creating instance of { model .__name__ } with data: { data } " )
302
308
return model (** data )
@@ -501,10 +507,7 @@ def sample_and_paginate_collection(
501
507
# So, you can directly use it to create the response model instances.
502
508
data = [VPD (** item ) for item in raw_data ]
503
509
else :
504
- data = [create_model_instance (response_model , item ) for item in raw_data ]
505
- if data and unit :
506
- for item in data :
507
- convert_temperature (item , unit )
510
+ data = [create_model_instance (response_model , item , unit ) for item in raw_data ]
508
511
509
512
# Re-run for total page count
510
513
pipeline .append ({"$count" : "total" })
@@ -535,8 +538,6 @@ async def historical_data_route(
535
538
536
539
# TODO - Refactor this to support paid collections
537
540
collection_name = "FreeTier"
538
- if not isinstance (entity , Temperature ):
539
- unit = None
540
541
541
542
return sample_and_paginate_collection (
542
543
entity ,
0 commit comments