Question

J'ai deux modèles liés l'un à plusieurs: Publier et 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();

Je veux obtenir une liste des postes, commandés par la date du dernier commentaire. Si j'écrire une requête SQL personnalisée, il ressemblerait à ceci:

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

Comment puis-je faire même chose en utilisant ORM django?

Était-ce utile?

La solution

from django.db.models import Max

Post.objects.distinct() \
            .annotate(date_of_last_comment=Max('comment__date_added')) \
            .order_by('-date_of_last_comment')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top