tags:

views:

160

answers:

2

In my quest to understand queries to Django models I've been trying to get the last 3 added valid Avatar models with a query like:

newUserAv = Avatar.objects.filter(valid=True).order_by("date")[:3]

However this gives me the first three avatars added ordered by date. I'm sure this is so simple but I've had trouble finding it in the Django docs, how do I selected the LAST three avatar objects instead of the first?

+6  A: 

Put a hyphen before the field name.

.order_by('-date')
Deniz Dogan
Its annoyingly easy when you know how - thanks you :)
Tristan
Documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields
S.Lott
A: 

Reverse order with .reverse()

newUserAv = Avatar.objects.filter(valid=True).order_by("date").reverse()[:3]
tuergeist
That works with lists, but explicitly not with querysets - try it and you get the message "Negative indexing is not supported".
Daniel Roseman
@daniel: ok, I reverted my answer
tuergeist