2011-06-09 21 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')) 
相关问题