2011-06-09 60 views
1

帖子有用戶和日期屬性。不同用戶的最新帖子

我怎樣才能把這個

posts = Post.objects.order_by('-date')[:30] 

給我30級或更少的職位由每個用戶由過去後的?

例如,如果我有4個帖子存儲,3個來自post.user =「Benny」和1個來自post.user =「Catherine」,它應該從Benny返回1個帖子,並從Catherine按日期排序返回1個帖子。

回答

3

我可能會使用annotate,您可能可以使用extra來查看單個查詢。

posts = [] 
for u in User.objects.annotate(last_post=Max('post__date')).order_by('-last_post')[:30]: 
    posts.append(u.post_set.latest('date')) 

你也可以使用raw,這將讓你寫一個SQL查詢,但仍返回模型實例。例如:

sql = """ 
SELECT * FROM app_post 
WHERE app_post.date IN 
    (SELECT MAX(app_post.date) FROM app_post 
    GROUP BY app_post.user_id) 
ORDER BY app_post.date DESC 
""" 
posts = list(Post.objects.raw(sql)) 
+0

我同意你的看法。但是,應該有'order_by(' - last_post')'和'posts.append(u.post_set.latest('date'))'獲得**最新的帖子。 – srusskih 2011-06-09 06:01:31

+0

@srusskih有幫助,呃? – zeekay 2011-06-09 06:28:46

0

未經測試,但你也許可以做到這一點

from django.db.models import Max 
Post.objects.all().annotate(user=Max('date')) 
相關問題