[Fixed]-Python3: Loop over objects and add attributes to an array or object

1👍

Accessing Python dictionaries is much easier than using setattr.
You have two options. Either create a dictionary with IDs as Keys or just a simple list.

import json

data = {}
camera_logs = CameraLog.objects.filter(camera_id=camera_id)
for log in camera_logs :
    data[log.id] = log.celsius

return Response(json.dumps(data))

in above solution you will have a dictionary with ID of CameraLog as a KEY, and as value you will have celsius. Basically your json will look like this:

{
   1: 20,
   2: 19,
   3: 21
}

Second approach is to send a simple list of values, but I guess you would like to have info, what camera had what temp

import json

data = []
camera_logs = CameraLog.objects.filter(camera_id=camera_id)
for log in camera_logs :
    data.append(log.celsius)

return Response(json.dumps(data))

Edit to an answer

If you wish to have a list of dicts, make something like this:

import json

data = []
camera_logs = CameraLog.objects.filter(camera_id=camera_id)
for log in camera_logs :
    data.append({
        'camera_id': log.id,
        'celsius': log.celsius,
        'fahrenheit': log.fahrenheit
     })

return Response(json.dumps(data))
👤sebb

0👍

You can enhance your query by only selecting the attributes that you need from a queryset using .values_list.

import json

camera_logs = CameraLog.objects.filter(camera_id=camera_id).values_list(
    'celsius', 'fahrenheit')
data = [{"celcius": cel, "fahrenheit": fahr} for cel, fahr in camera_logs]
return Response(json.dumps(data))

Leave a comment