【问题标题】:Use Django's ORM to find most recent message within each message thread使用 Django 的 ORM 在每个消息线程中查找最新消息
【发布时间】:2013-09-24 20:11:45
【问题描述】:

我有一个与 Facebook 非常相似的消息传递功能,每个人都可以向另一个人发送消息,创建一个新的消息线程,这两个人之间的每条后续消息都将出现在同一个线程上。我创建了一个“消息”数据表,其中存储了所有消息以及 thread_id,如下所示:

id    message    sender_id    receiver_id    thread_id    message_date
1     Hello Bob  3            5              1            ...
2     Hello Jon  5            3              1            ...
3     Hi Jane    2            4              2            ...
4     Hi Sara    4            2              2            ...

我想使用 Django 的 ORM 仅返回每个唯一 thread_id 的最新消息。我如何在 Django 中做到这一点?

【问题讨论】:

    标签: django postgresql orm


    【解决方案1】:

    如果你使用 Postgres,你可以做 Message.objects.order_by('thread_id').distinct('thread_id') 其他任何事情,你可以做这样的事情:

    #first, grab all Threads
    threads = Thread.objects.all().prefetch_related('message_set')
    
    # loop through the threads, and get the latest message
    for thread in threads:
        latest_message = thread.message_set.latest('message_date')
    

    【讨论】:

      【解决方案2】:

      类似:

      from django.db.models import Max
      from myapp.models import Message
      Message.objects.annotate(message_date=Max('message_date')).values('id__max')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-09
        • 1970-01-01
        • 2013-11-24
        • 2012-12-20
        相关资源
        最近更新 更多