On 3 avr, 23:12, Adam Tonks <[email protected]> wrote:
> 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 you really did test on the very same data set, same forum, *same
thread* (IOW ; same value for "self.pk") etc, you would'nt get an
IndexError, so there's obviously something different.


> 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]

This returns all posts, whatever thread they belongs to.

>
> I have no idea why adding the [0] to get the first result of the queryset is 
> causing it to return an empty queryset.

It's not "causing it to return an empty queryset", it's raising an
index error because your queryset is already empty.

> If anyone has any suggestions as to what I could do, it'd be much appreciated.

try:
    Post.objects.filter(thread = self.pk).order_by('created')[0]
except IndexError:
   # just so you know your queryset is really empty
   # comment this out (or even better remove it) once you made sure
   # the error was in your test, not in Django
   if Post.objects.filter(thread = self.pk).count():
       raise AssertionError("Something has gone terribly wrong")

   # here you may want to either return None if an empty thread is ok
for your,
   # or raise some specific exception else
   return None

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

Reply via email to