Home » Python » django order_by query set, ascending and descending

django order_by query set, ascending and descending

Posted by: admin November 1, 2017 Leave a comment

Questions:

How can I order by descending my query set in django by date?

Reserved.objects.all().filter(client=client_id).order_by('check_in')

I just want to filter from descending all the Reserved by check_in date.

Answers:
Reserved.objects.filter(client=client_id).order_by('-check_in')

Notice the - before check_in.

Django Documentation

Questions:
Answers:
Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen “-” in front of “check_in” indicates descending order. Ascending order is implied.

We don’t have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here:
https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

Questions:
Answers:

It works removing .all():

Reserved.objects.filter(client=client_id).order_by('-check_in')

Questions:
Answers:

You can also use the following instruction:

Reserved.objects.all().filter(client=client_id).order_by('check_in').reverse()

Questions:
Answers:

for ascending order:

Reserved.objects.filter(client=client_id).order_by('check_in')

for descending order:

1.  Reserved.objects.filter(client=client_id).order_by('-check_in')

or

2.  Reserved.objects.filter(client=client_id).order_by('check_in')[::-1]

Questions:
Answers:

This is working for me.

latestsetuplist = SetupTemplate.objects.order_by('-creationTime')[:10][::1]