Sunday, April 3, 2011

Odd problem with queryset

I have a function in a model to return the first post in a forum thread.  At the moment, it looks like this:
return Post.objects.filter(thread = self.pk).order_by('created')
When I run it in my test forum, the code returns two posts:
[<Post: This post is a test post to display when the...>, <Post: This is a reply to the test post.>]
I then add a [0] to the end of the statement, to just return the first item, creating this return statement:
return Post.objects.filter(thread = self.pk).order_by('created')[0]
This, however, gives me "Caught IndexError while rendering: list index out of range".
The only thing I changed the entire time was adding the [0]. I tested on the same forum, with the same data etc.
If I remove the filter part (making the statement below), it works fine, returning the first post in the queryset.
return Post.objects.order_by('created')[0]
I have no idea why adding the [0] to get the first result of the queryset is causing it to return an empty queryset. If anyone has any suggestions as to what I could do, it'd be much appreciated.
Traceback: http://dpaste.com/hold/528447/

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

No comments:

Post a Comment