1

コメント数でクエリセットをフィルタリングし、コメント数で降順で並べ替えるにはどうすればよいですか?

私は何かをしようとしましPost.objects.filter(comment_count > 0).order_by('-comment_count')たが、それはうまくいきませんでした。

ありがとう!

私の投稿モデル:

class Post(models.Model):
 nickname = models.CharField(max_length=200, default=u'anonymous')
 body = models.TextField()
 pub_date = models.DateTimeField('Date Published', auto_now_add=True)
 up_date = models.DateTimeField('Date Updated', auto_now=True)
 category = models.ForeignKey(Category, related_name='post_category')
 counter = models.IntegerField(default=0)
 status = models.IntegerField(choices=POST_STATUS, default=0)
 votes = models.IntegerField('Votes', default=0)

編集:

次のコードを追加しただけです

from django.contrib.contenttypes import generic
from django.contrib.comments.models import Comment

comments = generic.GenericRelation(Comment, object_id_field="object_pk")

そして私の見解では:

post_list = Post.objects.annotate(comment_count=Count('comments')).filter(status=STATUS.ACCEPTED).filter(comment_count__gt=0).order_by('-comment_count')

モデルとビューのコードを修正しました。彼らは今、うまくいっています。

ありがとう!

4

1 に答える 1

2

「注釈」の使用; このようなもの:

from django.db.models import Count
Post.objects.annotate(comment_count=Count('comments')).filter(comment_count__gt=0).order_by('-comment_count')

詳細については、次を参照してください: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

于 2011-05-02T09:28:36.383 に答える