通过反向ForeignKey DateTimeField排序?

时间:2014-01-05 10:04:27

标签: python django

考虑这两个模型:

class pm_thread(models.Model):
    subject = models.CharField(max_length=200)
    participants = models.ManyToManyField(User)

    def latest_message(self):
        message = self.message_set.order_by('-datetime')
        if message:
            return message[0]
        return None

class pm_message(models.Model):
    thread = models.ForeignKey(pm_thread, related_name='message_set')
    user = models.ForeignKey(User, related_name='sent_message')
    datetime = models.DateTimeField(auto_now_add=True)
    content = models.TextField()

如何在最新消息日期之前订购pm_thread查询?例如:

threads = pm_thread.objects.filter(participants=request.user).order_by(latest_message.datetime)

1 个答案:

答案 0 :(得分:3)

尝试:

threads = pm_thread.objects.filter(participants=request.user).order_by('-pm_message__datetime')