我有一个看起来像这样的views.py:
category = Category.objects.get(id=categoryid)
#posts = get_list_or_404(Post, category=categoryid)
posts = Post.objects.filter(category=categoryid,is_comment=0).order_by('-published')
all_posts = []
for p in posts:
all_posts += [(x.id, x.marked_read_on, p, \
Unread.objects.filter(marked_read_on__isnull=True, \
user=request.user,comment__post=p.id).count(), \
Unread.objects.filter(user=request.user,comment__post=p.id).count(), \
#1
) \
#for x in p.unread_set.filter(post=p.id)]
for x in p.unread_set.filter(post=p.id).annotate(Count('post')).order_by('post')]
对于for x in p.unread_set.filter(post=p.id).annotate(Count('post')).order_by('post')]
我得到下面的sql查询:(没有错误)
SELECT `message_unread`.`id`, `message_unread`.`user_id`, `message_unread`.`post_id`, `message_unread`.`comment_id`, `message_unread`.`category_id`, `message_unread`.`marked_unread_on`, `message_unread`.`marked_read_on`, COUNT(`message_unread`.`post_id`) AS `post__count` FROM `message_unread` WHERE (`message_unread`.`post_id` = 4 AND `message_unread`.`post_id` = 4 ) GROUP BY `message_unread`.`id` ORDER BY `message_unread`.`post_id` ASC
我只想要这个部分:
GROUP BY
message_unread
.id
成为:
message_unread
我只是想通过post_id对结果进行分组。仅供参考,应用程序的名称是“消息”,这就是查询具有“message_”前缀的原因。
我该怎么做?
更新,我的models.py看起来像这样:
id
答案 0 :(得分:2)
以下是unread.objects.filter(post=p.id).values(message_unread.id).order_by().annotate(Count('post'))
>>> from django.db.models import Count
>>> m=Unread.objects.filter(post__id='1').values('id').order_by().annotate(Count('post'))
>>> m
[{'id': 1L, 'post__count': 1}]
>>> m.values()
[{'marked_read_on': datetime.datetime(2011, 3, 3, 22, 3, 33), 'user_id': 1L, 'comment_id': 1L, 'post_id': 1L, 'marked_unread_on': datetime.datetime(2011, 3, 3, 22, 3, 29), 'category_id': 1L, 'id': 1L, 'post__count': 1}]
以下查询
>>> print m.query
SELECT `mytest_unread`.`id`, COUNT(`mytest_unread`.`post_id`) AS `post__count` FROM `mytest_unread` WHERE `mytest_unread`.`post_id` = 1 GROUP BY `mytest_unread`.`id`, `mytest_unread`.`id` ORDER BY NULL