Advertisement
Advertisement


django order_by query set, ascending and descending


Question

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.

2016/06/10
1
306
6/10/2016 9:44:13 AM

Accepted Answer

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

Notice the - before check_in.

Django Documentation

2016/10/18
577
10/18/2016 3:06:12 AM

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

2014/01/20

You can also use the following instruction:

Reserved.objects.filter(client=client_id).order_by('check_in').reverse()
2019/07/10

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]
2016/02/25

It works removing .all():

Reserved.objects.filter(client=client_id).order_by('-check_in')
2014/01/21

Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.

class MyModel(models.Model):

    check_in = models.DateField()

    class Meta:
        ordering = ('-check_in',)
2018/02/26

Source: https://stackoverflow.com/questions/9834038
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]