On 16 août, 08:14, shacker <shac...@birdhouse.org> wrote:
> I'm trying to figure out why this works:
>
> >>> comments = Comment.objects.all()
> >>>[c.content_object for c in comments]
>
> [returns a list of the objects the comments are attached to]
>
> But this doesn't:
>
> >>> c = Comment.objects.filter(id=111)
> >>> c
>
> [<Comment: Related object name here ...>]>>> c.content_object
>
> Traceback (most recent call last):
>   File "<console>", line 1, in <module>
> AttributeError: 'QuerySet' object has no attribute 'content_object'

Of course. As the error message says, 'c' is here a queryset, not a
model object. If you want to retrieve a single model object, you have
to use manager.get, not manager.filter, ie:

>>> c = Comment.objects.get(id=111)
>>> c
<Comment: Related object name here ...>
>>> c.content_object
# your content object here

> The problem I'm trying to solve is that I've got a context processor
> that retrieves recent comments:
>
> def recent_comments(request):
>     return {'recent_comments': Comment.objects.filter().order_by('-id')
> [:6]}
>
> But if an item has been unpublished but still has comments attached to
> it, it crashes. So I want to alter the query in the content processor
> to only grab comments on items that have publish=True.

You won't be able to do this in a single SQL query. A Q&D solution
might be:

def recent_comments(request):
    comments = Comment.objects.all().order_by('-id')
    recent_comments = []
    for comment in comments:
         if len(recent_comments) == 6: # XXX hardcoded, that's bad
             break
         content = comment.content_object()
         try:
              if content.publish:
                  recent_comments.append(comment)
         except AttributeError
              # content has no 'publish' attribute
              pass
    return dict(recent_comments=recent_comments)


If your comments are all on a same model class, you can possibly
optimize this by first retrieving a list of published objects AND the
content_type id for your model class, then filtering comments on these
values (implementation left as an exercice to the reader !-))

HTH

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to