[Django]-Django date query from newest to oldest

60👍

ordered_tasks = TaskItem.objects.order_by('-created_date')

The order_by() method is used to order a queryset. It takes one argument, the attribute by which the queryset will be ordered. Prefixing this key with a - sorts in reverse order.

👤mipadi

5👍

By the way you also have Django’s created_at field at your disposal:

ordered_tasks = TaskItem.objects.order_by('-created_at')
👤spedy

3👍

You can set your ordering in model Meta class. This will be the default ordering for the object,for use when obtaining lists of objects.

class TestModel(models.Model):
    ...
    created_at = models.DateField()
    ....

    class Meta:
       ordering = ['-created_at']

Or you can apply ordering to specific queryset.
TestModel.objects.order_by('-created_at')

Leave a comment