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.
5👍
By the way you also have Django’s created_at
field at your disposal:
ordered_tasks = TaskItem.objects.order_by('-created_at')
- [Django]-React Error: Target Container is not a DOM Element
- [Django]-Resize fields in Django Admin
- [Django]-How to get key value in django template?
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')
- [Django]-How to compare dates in Django templates
- [Django]-Django add extra field to a ModelForm generated from a Model
- [Django]-Django – is not a registered namespace
Source:stackexchange.com