Django:按向后相关字段属性排序
我有两个一对多相关的模型:帖子和评论:
class Post(models.Model):
title = models.CharField(max_length=200);
content = models.TextField();
class Comment(models.Model):
post = models.ForeignKey('Post');
body = models.TextField();
date_added = models.DateTimeField();
我想获取帖子列表,按最新评论的日期排序。如果我要编写一个自定义 SQL 查询,它将如下所示:
SELECT
`posts`.`*`,
MAX(`comments`.`date_added`) AS `date_of_lat_comment`
FROM
`posts`, `comments`
WHERE
`posts`.`id` = `comments`.`post_id`
GROUP BY
`posts`.`id`
ORDER BY `date_of_lat_comment` DESC
How can I do same thing using django ORM?
I have two models related one-to-many: a Post and a Comment:
class Post(models.Model):
title = models.CharField(max_length=200);
content = models.TextField();
class Comment(models.Model):
post = models.ForeignKey('Post');
body = models.TextField();
date_added = models.DateTimeField();
I want to get a list of posts, ordered by the date of the latest comment. If I would write a custom SQL query it would look like this:
SELECT
`posts`.`*`,
MAX(`comments`.`date_added`) AS `date_of_lat_comment`
FROM
`posts`, `comments`
WHERE
`posts`.`id` = `comments`.`post_id`
GROUP BY
`posts`.`id`
ORDER BY `date_of_lat_comment` DESC
How can I do same thing using django ORM?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)