Django:使用外键查询

Ali*_*uis 3 django

我有两个称为Thread和的模型Post。主题有0..*帖子。

现在,我需要一个查询,该查询将按线程中最新发布的日期时间对所有线程进行排序。如果线程中还没有发布,则线程创建的日期时间很重要。

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

Thread:
created_at = DateTimeField()

Post
thread = ForeignKey(Thread)
Run Code Online (Sandbox Code Playgroud)

我目前的方法行不通:

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')
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?

Wil*_*sem 5

您可以使用Max集合[Django-doc]注释这些,并使用Coalesce[Django-doc]函数作为后备机制,例如:

from django.db.models import Max
from django.db.models.functions import Coalesce

Thread.objects.annotate(
    latest_post=Coalesce(Max('post__created_at'), 'created_at')
).order_by('-latest_post')
Run Code Online (Sandbox Code Playgroud)

The latest_post is thus the timestamp of the maximum created_at of the related Post objects. In case there are no related Post objects, we fallback on the created_at field of the Thread.

  • 有用!你怎么这么快 你一定是个天才! (2认同)