Bring 4 limit each by combining the various filter conditions of sqlalchemy sentence???

Asked 2 years ago, Updated 2 years ago, 153 views

ended_94 = db.session.query(Ended_event).filter(Ended_event.league_id == 94).order_by(Ended_event.time.desc()).limit(4)
ended_99 = db.session.query(Ended_event).filter(Ended_event.league_id == 99).order_by(Ended_event.time.desc()).limit(4)
ended_123 = db.session.query(Ended_event).filter(Ended_event.league_id == 123).order_by(Ended_event.time.desc()).limit(4)
ended_207 = db.session.query(Ended_event).filter(Ended_event.league_id == 207).order_by(Ended_event.time.desc()).limit(4)

Each limit (4) is imported in the order of time value according to the height_id value, so can I change this to a line of command?

mysql sql sqlalchemy python

2022-09-22 13:56

1 Answers

For complex queries, just raw query.

The sample below is sqlite, and please refer to the link below for the data.

https://www.sqlitetutorial.net/sqlite-sample-database/

query = """SELECT * FROM (
    SELECT
        ROW_NUMBER () OVER ( 
            PARTITION BY Country
            ORDER BY FirstName
        ) RowNum, FirstName, LastName, country, CustomerId 
    FROM
        customers
    WHERE 
        country in ('Canada', 'USA')
) WHERE RowNum < 3"" # Canada, USA two each.

rows = session.execute(query)

for r in rows:
    print(r)

(1, 'Aaron', 'Mitchell', 'Canada', 32)
(2, 'Edward', 'Francis', 'Canada', 30)
(1, 'Dan', 'Miller', 'USA', 20)
(2, 'Frank', 'Harris', 'USA', 16)


# When you get it with the mapper
rows = session.query(customers).from_statement(query).all()
for r in rows:
    print(r.Country)

Canada
Canada
USA
USA


2022-09-22 13:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.