On 01/11/06, Gábor Farkas <[EMAIL PROTECTED]> wrote:
>
> Frankie Robertson wrote:
> > On 01/11/06, Gábor Farkas <[EMAIL PROTECTED]> wrote:
> >> samuel wrote:
> >>>>> I'm probably just not seeing it, but how do  I go about getting the
> >>>>> index of an item in a query set? I.E., this article is the Xth article
> >>>>> in this queryset of articles sorted by date.
> >>>> If you're looping through them in the template with the 'for' tag,
> >>>> each time through the loop you'll have access to a variable called
> >>>> 'forloop.counter' which has this information; the first time through
> >>>> it will be 1, the second time it will be 2, and so on.
> >>>>
> >>>> See http://www.djangoproject.com/documentation/templates/#for for 
> >>>> details.
> >>>>
> >>> Thanks but I guess I'm looking for something a bit different. Here's
> >>> exactly what I'm trying to do: I have  articles that are chunked into
> >>> groups of 10 arbitrarily based on their date. So when a new article is
> >>> added the groups change. When you go to an article page, I want to
> >>> display the chunk that the article belongs to. So if the article is
> >>> 19th, display a list of articles 11-20.
> >>>
> >>> If I'm thinking through this correctly, I need to know the articles
> >>> location in the queryset before I get to the template and then slice
> >>> the queryset as necessary. How would I go about this? Just iterate
> >>> through and backtrack when I get there?
> >>>
> >> if the number of articles is not too high, then simply generate their
> >> number in the view... like:
> >>
> >> queryset = Article.objects.all()
> >>
> >> items = list(enumerate(queryset))
> >>
> >> which is basically the same as:
> >>
> >> items = zip (range(queryset.count()), queryset)
> >>
> >> or, if you want it 1-based and not 0-based:
> >>
> >> items = zip (range(1,queryset.count()+1), queryset)
> >>
> >> the problem with these is that it fetches all the article-objects.
> >
> > Since the only way to do this is programmatically in python it might
> > be better to use raw sql for this instead.
> >
>
> hmm.. how?

Oh, I didn't really read the question carefully enough. You're right,
I don't think there is a standard SQL function to do this. The above
solution is pretty good. It could be done without having to fetch them
all.

Something like (obviously this could be less messy):

page = 1
queryset = Article.order_by('-pub_date')[(page-1)*10:page*10-1]
items = zip(range((page-1)*10+1, queryset.count()+1), queryset)

>
> gabor
>
> >
>


-- 
http://grimboy.co.uk

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

Reply via email to