Is there any ways to combine two rows of table into one row using Django ORM?

Viewed 676

I have a table which has columns named measured_time, data_type and value.
In data_type, there is two types, temperature and humidity. I want to combine two rows of data if they have same measured_time using Django ORM.
I am using Maria DB.

Using Raw SQL, The following Query does what I want to.

SELECT  T1.measured_time, T1.temperature, T2.humidity
FROM ( SELECT CASE WHEN data_type = 1 then value END as temperature,
CASE WHEN data_type = 2 then value END  as humidity ,
measured_time FROM data_table) as T1,
( SELECT CASE WHEN data_type = 1 then value END as temperature ,
CASE WHEN data_type = 2 then value END  as humidity , 
measured_time FROM data_table) as T2 
WHERE T1.measured_time = T2.measured_time and 
T1.temperature IS NOT null and T2.humidity IS NOT null and 
DATE(T1.measured_time) = '2019-07-01' 

Original Table

| measured_time       | data_type | value |
|---------------------|-----------|-------|
| 2019-07-01-17:27:03 | 1         | 25.24 |
| 2019-07-01-17:27:03 | 2         | 33.22 |

Expected Result

| measured_time       | temperaure | humidity |
|---------------------|------------|----------|
| 2019-07-01-17:27:03 | 25.24      | 33.22    |
1 Answers

I've never used it and so can't answer in detail, but you can feed a raw SQL query into Django and get the results back through the ORM. Since you have already got the SQL this may be the easiest way to proceed. Documentation here

Related