Querysets and ROW_NUMBER

2,076 views
Skip to first unread message

adrian

unread,
Apr 7, 2009, 11:16:00 PM4/7/09
to Django users
Was wondering if anyone can point me in the right direction here, what
would be the Django style way to annotate a set with a row number in
some way like:-

Book.objects.all().order_by('date_added').annotate(row_num=RowNumber
('id'))

Unfortunately PostgreSQL does not support ROW_NUMBER yet so I can't
just tack this on with .extra(). Thanks in advance for any tips!

Tim Chase

unread,
Apr 8, 2009, 6:22:04 AM4/8/09
to django...@googlegroups.com
adrian wrote:
> Was wondering if anyone can point me in the right direction here, what
> would be the Django style way to annotate a set with a row number in
> some way like:-
>
> Book.objects.all().order_by('date_added').annotate(row_num=RowNumber
> ('id'))

Well many times the "Django style way" also happens to be the
Python way:

books = Book.objects.all().order_by('date_added')
for row_num, book in enumerate(books):
do_something(row_num, book)

-tim

adrian

unread,
Apr 8, 2009, 8:17:07 PM4/8/09
to Django users
Thanks for the advice Tim. I ended up doing something similar,
although not as elegant as your solution. I'll give it a go ;)

cheers
adrian
Reply all
Reply to author
Forward
0 new messages