django模型orm,一个关系查询问题,很难描述它

时间:2015-05-07 04:25:10

标签: mysql django orm

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='')

现在我想选择所有主题和每个主题的最后一篇文章。

像这样:

1,topic1为topic1的最后一篇文章

2,topic2为topic2的最后一篇文章

3,topic3为topic3的最后一篇文章

我应该如何构造orm查询,它应该只是一个sql查询字符串。

请原始的sql字符串。

2 个答案:

答案 0 :(得分:0)

如何在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

答案 1 :(得分:0)

raw 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表达式可以做到这一点?