Django: ordering by backward related field property

Posted by Silver Light on Stack Overflow See other posts from Stack Overflow or by Silver Light
Published on 2010-03-30T08:34:04Z Indexed on 2010/03/30 8:43 UTC
Read the original article Hit count: 296

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-orm