How can I tell the Django ORM to reverse the order of query results?

Question:

In my quest to understand queries against 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 instead gives me the first three avatars added ordered by date. I’m sure this is simple, but I’ve had trouble finding it in the Django docs: how do I select the last three avatar objects instead of the first three?

Asked By: Tristan Brotherton

||

Answers:

Put a hyphen before the field name.

.order_by('-date')
Answered By: Deniz Dogan

create list and

def messages_to_list(messages):
    result = []
    for message in messages:
        result.append(message_to_list(message))
    result.reverse()
    return result

def message_to_list(message):
    return {
    'member': str(message.member),  
    'message': str(message.message),
    'pub_date': str(message.pub_date.strftime(" %B %d,%Y, %A %I:%M%p ")),
    'admin': message.admin
    }

The result above will be ordered by pub_date descending, then by headline ascending.

Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')

If we had a Python sequence and looked at seq [-5:], we would see the fifth (last) element first. Django does not support this access mode (slicing from the end), because it cannot be done efficiently in SQL.
(((((((((((((((((((((((((((((

Answered By: Roman Rekrut
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.