0

我有两个一对多相关的模型:一个Post和一个Comment

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 做同样的事情?

4

1 回答 1

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')
于 2010-03-30T08:41:42.080 回答