如何在Django的相关模型上获取字段的最新值?

时间:2017-06-25 09:26:19

标签: django django-queryset annotate

我有以下型号:

class Timestamped(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Thread(Timestamped):
    user1 = models.ForeignKey(User, related_name='user1')
    user2 = models.ForeignKey(User, related_name='user2')

class Message(Timestamped):
    thread = models.ForeignKey(Thread)
    text = models.CharField(max_length=255)
    sender = models.ForeignKey(User)

我有一个QuerySet来获取所有线程,但我也希望在循环时显示每个线程的最新消息。

我已经提出以下内容来显示该消息的最新时间戳。

threads = Thread.objects.filter(Q(user1=request.user) | Q(user2=request.user))\
            .annotate(latest_msg=Max('message__modified')).order_by('-latest_msg')

如何显示消息文本?

1 个答案:

答案 0 :(得分:1)

threads = Thread.objects.filter(
            Q(user1=request.user) | Q(user2=request.user)
          ).annotate(
            latest_msg=Max('message__modified')
          ).values(
            'message__text',
            'fields you want to fetch'
          ).order_by('-latest_msg')[:1]