django model orm,关系查询问题,一言难尽

django model orm, a relationship query issue, hard to describe it

class Topic(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16,default='')

class Post(models.Model):
    id = models.AutoField(primary_key=True)
    topic = models.ForeignKey(Topic)
    time = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=16,default='')

现在我想 select 所有主题和每个主题的最后一个 post。

像这样:

1、topic1〉〉〈〉last post for topic1

2、topic2‖‖‖针对topic2post的last post

3、topic3》》》最后post for topic3

orm查询应该怎么构造,而且应该只有一个sql查询字符串

或原始 sql 字符串。

如何在 Topic 上将其设为 属性。像这样:

@property
def last_post(self):
    Post.objects.filter(topic=self).annotate(max_time=Max('time')).get(time=F('max_time'))

那么你可以针对一个话题做这个:

topic = Topic.objects.first()
topic.last_post

原始 sql:

SELECT * FROM
  (SELECT
  `post`.`topic_id` AS `topic_id`,
  `post`.`id` AS `id`,
  `post`.`time` AS `time`,
  `post`.`name` AS `name`
FROM `post` ORDER BY `time` DESC) AS `temp`
inner join `topic` on `topic_id` = `topic`.`id`
GROUP BY `topic_id`
ORDER BY `time` DESC;

有没有orm表达式可以做到这一点?