SQLAlchemy:每年查询最大数量

SQLAlchemy: Query max amount per year

我有一个模型,Photo 带有日期列。我正在制作一个照片库,它有一个概览视图,每年最多显示 5 张照片。

目前我有这个查询,并让它循环遍历手动制作的年份列表。
(即 for year in range(2000, 2016):

Photo.query \
.filter(extract('year', Photo.date)==year) \
.order_by(Photo.date) \
.limit(5) \
.all()

是否有更有效的方法(而不是 15 个查询)?此外,但不太重要的是,有没有一种方法可以根据照片存在的年份对年份进行排序(作为使用硬编码列表的替代方法)?

更新:我正在使用 sqlite3

假设 date 是唯一的,下面的查询应该适用于 sqlite:

# define aliases as we will need to join the table on itself
p1 = Photo
p2 = db.aliased(Photo, name='p2')

q = (
    p1.query
    # join *Photo* on itself and count the *rank* of current photo by counting the photos with date before it in the same year
    .join(p2, sa.and_(
        sa.func.extract("year", p1.date) == sa.func.extract("year", p2.date),
        p1.date >= p2.date,
    ))
    .group_by(p1.id)
    .having(sa.func.count() <= 5)
    .order_by(p1.date)  # This will automatically order by year and rank
)

如果date不是唯一的,但几乎是唯一的,结果将不会总是5行,但可以更多或更少。如果这些确实是 date 值(没有时间分量),请告诉我 - 应该很容易获得更可靠的解决方案。