2015-07-12 89 views
0

我有一個模型,Photo與日期列。我正在製作一個概覽視圖的相冊,每年最多顯示5張照片。SQLAlchemy:查詢每年最大金額

目前我有這個查詢,並通過手動製作的年份列表循環。
(即for year in range(2000, 2016):

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

有沒有一種更有效的方式來做到這一點(而不是15個的查詢)?此外,但不太重要,有沒有一種方法可以根據年份照片存在的年份(作爲使用硬編碼列表的替代方法)對年份進行排序?

UPDATE:我使用的sqlite3

+0

正確的查詢將取決於您正在使用的數據庫,你可以在你的問題中包括它? – SingleNegationElimination

+0

@SingleNegationElimination:done –

+0

我認爲這應該完成'group_by()',但不能指向一個很好的示例http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query。 Query.group_by –

回答

1

有了一個假設,即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值(沒有時間分量),請告訴我們 - 獲得更強大的解決方案應該很容易。