The query itself is correct and I am able to get the raw query set. I need to convert this into query set for further processing and I am facing below error.
Creating corresponding django query was hard for me and that is why I created SQL query, got the raw query set and now attempting to convert it to query set for further processing.
I have changed model and table names for anonymity.
queryset = Test1.objects.filter(id__in=RawSQL("SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM test1 WHERE EXISTS (SELECT * FROM test2 JOIN test3 ON test2.test3_id = test3.id AND test3.value = '{param}' JOIN test4 ON test2.test4_id = test4.id AND test4.test1_id = test1.id) ORDER BY test1.start_time DESC".format(param=val)))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'params'
Here is the formatted raw query
SELECT
DISTINCT ON (test1.start_time, test1.id) test1.id,
test1.name,
test1.start_time
FROM
test1
WHERE
EXISTS (
SELECT
*
FROM
test2
JOIN test3 ON test2.test3_id = test3.id
AND test3.value = '{param}'
JOIN test4 ON test2.test4_id = test4.id
AND test4.test1_id = test1.id
)
ORDER BY
test1.start_time DESC.format(param = val)
)