【问题标题】:Django: ordering by backward related field propertyDjango:按向后相关的字段属性排序
【发布时间】:2010-03-30 08:34:04
【问题描述】:

我有两个一对多相关的模型:PostComment

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

【问题讨论】:

    标签: django django-orm


    【解决方案1】:
    from django.db.models import Max
    
    Post.objects.distinct() \
                .annotate(date_of_last_comment=Max('comment__date_added')) \
                .order_by('-date_of_last_comment')
    

    【讨论】:

    • 对不起——distinct() 是我的答案的早期版本留下的。它可能没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2013-05-11
    • 2015-02-18
    相关资源
    最近更新 更多