Django ORM 查询每个用户的最后一条评论


Model定义伪代码


 class Comment():
   user_id
   text
   create_time

查询user_id in [1,2,3,4,5]中的的最后一条评论,用Django ORM怎么写? 如果不行的话,SQL怎么写呢

sql django orm

kendnd 9 years, 10 months ago

可以使用 __in ,示例如下:


 Comment.objects.filter(user_id__in=[1,2,3,4,5]).order_by['-create_time'][0]

官方文档在 这里

lixiang answered 9 years, 10 months ago

如果你的comment_id是自增长的话


 sql


 select * from comments where comment_id in (
    select max(comment_id) as comment_id from comments
    where user_id in (1, 2, 3, 4, 5)
    group by user_id
)

如果comment_id不是自增长,create_time也可以将就,同一用户应该不会出现create_time重复的情况


 sql


 select * from comments where create_time in (
    select max(create_time) as create_time from comments
    where user_id in (1, 2, 3, 4, 5)
    group by user_id
) and user_id in (1, 2, 3, 4, 5)

puruspa answered 9 years, 10 months ago

Your Answer