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.
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
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',)
If for some reason you have null values you can use the F function like this:
from django.db.models import F
Reserved.objects.all().filter(client=client_id).order_by(F('check_in').desc(nulls_last=True))
So it will put last the null values. Documentation by Django: https://docs.djangoproject.com/en/stable/ref/models/expressions/#using-f-to-sort-null-values
Reserved.objects.filter(client=client_id).earliest('check_in')
Or alternatively
Reserved.objects.filter(client=client_id).latest('-check_in')
Here is the documentations for earliest()
and latest()