Reputation: 45922
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?
Upvotes: 0
Views: 433
Reputation: 125167
from django.db.models import Max
Post.objects.distinct() \
.annotate(date_of_last_comment=Max('comment__date_added')) \
.order_by('-date_of_last_comment')
Upvotes: 2