Format Python Query

Asked

Viewed 41 times

1

I want to adjust my Python query so that I can correctly generate a chart in Chart.js.

I have the following code for query and generation of json file

def get(self, request, format=None):
    weatherData = WeatherData.objects.filter(row_id=1, sensor_id=1)
    date = [obj.date for obj in weatherData]
    value = [float(obj.value) for obj in weatherData]

    context = {
        'date': json.dumps(date, default=json_serial),
        'value': json.dumps(value),
    }
    return Response(context)

But this code is generating a file in the following format

{'date': '["2019-09-25T17:57:07+00:00", "2019-09-25T17:57:55+00:00", "2019-09-26T12:19:31.694958+00:00", "2019-09-30T01:43:21+00:00", "2019-09-30T17:06:58+00:00", "2019-09-30T17:11:39+00:00", "2019-09-30T17:12:03+00:00", "2019-09-30T17:13:51+00:00", "2019-09-30T17:16:05+00:00"]',  'value': '[10.0, 10.0, 4.5, 70.4,
70.4, 70.4, 70.4, 70.4, 70.4]'}

What I need is to generate a file in the format

{ date: "2019-09-30T17:16:05+00:00", value: 70.4 }, { date: "2019-09-30T17:16:05+00:00", value: 70.4 }

What I am doing wrong not to be generating my JSON file this way?

1 answer

2

You have only an eternal object, weatherData, and is creating two separate lists, one for the date

date = [obj.date for obj in weatherData]

and another for values:

value = [float(obj.value) for obj in weatherData]

If you only need a list that each item has two date and value, just do:

context = [{'date': obj.date, 'value': float(obj.value)} for obj in weatherData]

So you will be iterating only once on your original object and creating a list of dictionaries containing each key date and the value.

And return in response Response(context).

  • Thank you very much. Problem solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.