views:

44

answers:

1

Hello!

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?

+1  A: 
from django.db.models import Max

Post.objects.distinct() \
            .annotate(date_of_last_comment=Max('comment__date_added')) \
            .order_by('-date_of_last_comment')
Ben James
Thanks! This works without distinct() too. Is it necessary?
Silver Light
Sorry -- `distinct()` was cruft left from an earlier version of my answer. It probably works without.
Ben James