The Python Oracle

django order_by query set, ascending and descending

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle

--

Chapters
00:00 Django Order_by Query Set, Ascending And Descending
00:18 Accepted Answer Score 896
00:36 Answer 2 Score 89
01:02 Answer 3 Score 31
01:12 Answer 4 Score 20
01:26 Thank you

--

Full question
https://stackoverflow.com/questions/9834...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #sorting

#avk47



ACCEPTED ANSWER

Score 896


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

Notice the - before check_in.

- before column name mean "descending order", while without - mean "ascending".

Django Documentation




ANSWER 2

Score 89


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




ANSWER 3

Score 31


You can also use the following instruction:

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



ANSWER 4

Score 20


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]