1
我有一個views.py看起來是這樣的:Django的:集團通過澄清
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
成爲: GROUP BY
message_unread
。 post_id
我只是想通過post_id對結果進行分組。僅供參考,應用程序的名稱是「消息」,這就是爲什麼查詢具有「message_」前綴。
我該怎麼做?
更新,我的models.py如下:
class Category(models.Model):
name = models.CharField(max_length=120)
group = models.ForeignKey(Group)
def __unicode__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=250)
#slug = models.SlugField(max_length=250, unique=True)
body = models.TextField()
published = models.DateTimeField(default=datetime.now)
category = models.ForeignKey(Category)
group = models.ForeignKey(Group)
user = models.ForeignKey(User)
is_comment = models.BooleanField(default=0)
def __unicode__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comment_parent')
comment = models.ForeignKey(Post)
def __unicode__(self):
return comment.title
class Unread(models.Model):
user = models.ForeignKey(User)
post = models.ForeignKey(Post)
comment = models.ForeignKey(Comment, null=True, blank=True)
category = models.ForeignKey(Category)
marked_unread_on = models.DateTimeField(null=True, blank=True)
marked_read_on = models.DateTimeField(null=True, blank=True)
招呼舒尚特,感謝,但它組查詢仍然不適合我。我已經更新了我的文章,幷包含了我的模型,以澄清字段關係。 – wenbert 2011-03-03 16:14:58
>>> print m.query SELECT'mytest_unread'.''',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 – sush 2011-03-03 16:52:00