I am trying to write the following SQL query with sqlalchemy ORM:
SELECT * FROM (SELECT *, row_number() OVER(w) FROM (select distinct on (grandma_id, author_id) * from contents) as c WINDOW w AS (PARTITION BY grandma_id ORDER BY RANDOM())) AS v1 WHERE row_number <= 4;
This is what I have done so far:
s = Session() unique_users_contents = (s.query(Content).distinct(Content.grandma_id, Content.author_id) .subquery()) windowed_contents = (s.query(Content, func.row_number() .over(partition_by=Content.grandma_id, order_by=func.random())) .select_from(unique_users_contents)).subquery() contents = (s.query(Content).select_from(windowed_contents) .filter(row_number >= 4))
As you can see, it is pretty much modeled, but I have no idea how to refer to the row_number() result of a subquery from an external query where. I tried something like windowed_contents.c.row_number and added the label() call to the func function, but it didn’t work, I could not find any similar example in official docs or in stackoverflow.
How can I do that? And also, can you suggest a better way to make this request?
source share