我有两个模型,称为Thread
和Post
。一个主题帖拥有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')
有人能帮助我吗?