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

PythonDjango

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

Put a hyphen before the field name.

.order_by('-date')

Solution 2 - Python

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. (((((((((((((((((((((((((((((

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTristan BrothertonView Question on Stackoverflow
Solution 1 - PythonDeniz DoganView Answer on Stackoverflow
Solution 2 - PythonRoman RekrutView Answer on Stackoverflow