Django:按向后相关的字段属性排序

时间:2010-03-30 08:34:05

标签: django django-orm

我有两个与一对多相关的模型:发布评论

class Post(models.Model):
    title   = models.CharField(max_length=200);
    content = models.TextField();

class Comment(models.Model):
    post    = models.ForeignKey('Post');
    body    = models.TextField();
    date_added = models.DateTimeField();

我想获得一个帖子列表,按最新评论的日期排序。如果我要编写自定义SQL查询,它将如下所示:

SELECT 
    `posts`.`*`,
    MAX(`comments`.`date_added`) AS `date_of_lat_comment`
FROM
    `posts`, `comments`
WHERE
    `posts`.`id` = `comments`.`post_id`
GROUP BY 
    `posts`.`id`
ORDER BY `date_of_lat_comment` DESC

如何使用django ORM做同样的事情?

1 个答案:

答案 0 :(得分:2)

from django.db.models import Max

Post.objects.distinct() \
            .annotate(date_of_last_comment=Max('comment__date_added')) \
            .order_by('-date_of_last_comment')