Django:使用外键查询

3

我有两个模型,称为ThreadPost。一个主题帖拥有0..*篇帖子。

现在,我需要一个查询,按照主题帖中最新帖子的日期时间排序获取所有主题帖。如果主题帖中还没有帖子,则主题帖创建的日期时间很重要。

说实话,我对数据库查询有点不知所措。

Thread:
created_at = DateTimeField()

Post
thread = ForeignKey(Thread)

我的现有方法不起作用:

newest = Post.objects.filter(thread=OuterRef('pk')).order_by('-created_at')
threads = Thread.objects.annotate(
    latest_post=Case(
        When(Exists(Subquery(newest.values_list('created_at')[:1])),
             then=Value(Subquery(
                newest.values_list('created_at')[:1]),
            ),
            default=Value(Thread.created_at)))).order_by('-latest_post')

有人能帮助我吗?

1个回答

5
你可以使用 Max 聚合函数 [Django-doc] 对它们进行注释,并使用 Coalesce 函数 [Django-doc] 作为后备机制,例如:
from django.db.models import Max
from django.db.models.functions import Coalesce

Thread.objects.annotate(
    <b>latest_post=Coalesce(Max('post__created_at'), 'created_at')</b>
).order_by('-latest_post')

latest_post是与相关的Post对象中最大的created_at时间戳。如果没有相关的Post对象,我们会使用Threadcreated_at字段作为后备。


2
它运行了!你怎么这么快就做到了呢?你一定是个天才! - Aliquis
1
@Aliquis:这只是练习使用注释/聚合的过程 :) - Willem Van Onsem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接