2010-03-30 7 views
0

J'ai deux modèles liés l'un à plusieurs: un post et Commentaire:Django: commande par propriété domaine connexe en arrière

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?

Répondre

2
from django.db.models import Max 

Post.objects.distinct() \ 
      .annotate(date_of_last_comment=Max('comment__date_added')) \ 
      .order_by('-date_of_last_comment') 
+0

Merci! Cela fonctionne sans distinct() aussi. Est-ce nécessaire? –

+0

Désolé - 'distinct()' était à gauche d'une version antérieure de ma réponse. Cela fonctionne probablement sans. –