Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

People also ask

How do I reverse a relation in Django?

Thats' where related name or the reverse relationship comes in. Django, by defaults gives you a default related_name which is the ModelName (in lowercase) followed by _set - In this case, It would be profile_set , so group. profile_set . However, you can override it by specifying a related_name in the ForeignKey field.

What is Django's ORM?

The Django web framework includes a default object-relational mapping layer (ORM) that can be used to interact with application data from various relational databases such as SQLite, PostgreSQL and MySQL. The Django ORM is an implementation of the object-relational mapping (ORM) concept.

Can we order data in descending order in Django?

When we read the data from the model, Django returns queryset. Django has order_by method to sort the queryset in ascending and descending order. You can order the queryset on any field.


Put a hyphen before the field name.

.order_by('-date')

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