(This is a rewritten version of a deleted question from earlier today.)
I'm using the SQLAlchemy ORM as part of a Flask app, with MySQL as a backend, and I'm trying to write a query to return a list of entries surrounding a particular entry. While I have a working query in SQL, I'm unsure how to code it in SQLA. The docs for CTE in the ORM show a very complicated example, and there aren't many other examples I can find.
For now assume a very simple table that only contains words:
class Word(db.Model):
__tablename__ = 'word'
id = db.Column(db.Integer, primary_key=True)
word = db.Column(db.String(100))
If I want the 10 words before and after a given word (with an id of 73), an SQL query that does what I need is:
WITH cte AS (SELECT id, word, ROW_NUMBER() OVER (ORDER BY word) AS rownumber FROM word)
SELECT * FROM cte
WHERE rownumber > (SELECT rownumber FROM cte WHERE cte.id = 73) - 10
AND rownumber < (SELECT rownumber FROM cte WHERE cte.id = 73) + 10
ORDER BY rownumber;
I can't figure out the next step, however. I want to get a list of Word objects. I'd imagine that the first part of it could be something like
id = 73
rowlist = db.session.query(Word.id, db.func.row_number()).filter(Word.id == id).order_by(Word.word).cte()
but even if this is right, I don't know how to get this into the next part; I got bogged down in the aliased bits in the examples. Could someone give me a push in the right direction?