The Python Oracle

django order_by query set, ascending and descending

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization

--

Chapters
00:00 Question
00:28 Accepted answer (Score 834)
00:45 Answer 2 (Score 86)
01:13 Answer 3 (Score 41)
01:39 Answer 4 (Score 28)
01:53 Thank you

--

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

Accepted answer links:
[Django Documentation]: https://docs.djangoproject.com/en/dev/re...

Answer 2 links:
https://docs.djangoproject.com/en/dev/to...

--

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]