Джанго: Группа По уточнениям - PullRequest
1 голос
/ 03 марта 2011

У меня есть файл 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 <code>message_unread. id

Стать: GROUP BY <code>message_unread. post_id

Я просто хочу сгруппировать свои результаты по post_id.К вашему сведению, название приложения - «message», поэтому запрос имеет префикс «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)

1 Ответ

2 голосов
/ 03 марта 2011

Ниже приведен запрос для группы по 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
...