views:

24

answers:

1

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' 

In both cases, each "c" is a Comment instance. So why does c have a content_object property in the first case but not in the second? Thanks.

+3  A: 

No, in both cases you get a queryset. In the first one, you iterate through and get the content_object for every item in the queryset - but in the second one, you try and call it on the entire queryset, for some reason. If you iterated through the second one in the same way as you do the first, it would work.

Alternatively, and this is probably what you actually wanted to do, you could use:

c = Comment.objects.get(id=111)

to get the actual Comment object with ID 111, rather than a queryset consisting of one element.

Daniel Roseman
Exactly right Daniel. Not sure how I missed that (it was late :), but thanks.
shacker