@
@
@nixbox2019-08-31 18:14:19
Python
@nixbox, 2019-08-31 18:14:19

How to get records from different tables sorted by date with pagination?

Hello.
Flask + SqlAlchemy project.
There are a couple of dozens of tables of the same type, from which you need to return the latest records, sorted by date.
Those. as a result that "timeline" of records from different tables turned out.
The tables are not related.
And how can pagination be implemented for such a function?
(It is necessary to get these records on request, for example, 10 pieces each, I pull them to the front with ajax)
I can't figure out how to implement this.
Thanks a lot!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-09-01
_

# the first subquery, select all ids from SOME_TABLE where some_field is not NULL
s1 = select([SOME_TABLE.c.id]).where(SOME_TABLE.c.some_field != None)

# the second subquery, select all ids from SOME_TABLE where some_field is NULL
s2 = select([SOME_TABLE.c.id]).where(SOME_TABLE.c.some_field != None)

# union s1 and s2 subqueries together and alias the result as "alias_name"
q = s1.union(s2).alias('alias_name')

# run the query and limit the aliased result to 10
session.query(q).limit(10)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question