Reputation: 645
I am building my first Django program from scratch and am running into troubles trying to print out items to the screen from newest to oldest. My model has an auto date time field populated in the DB as so:
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.utils import timezone
class TaskItem(models.Model):
taskn = models.CharField(max_length = 400)
usern = models.ForeignKey(User)
#Created field will add a time-stamp to sort the tasks from recently added to oldest
created_date = models.DateTimeField('date created', default=timezone.now)
def __str__(self):
return self.taskn
What is the line of code that would be abel to sort or print this information in order from newest creation to oldest?
Want to implement it into this call:
taskitems2 = request.user.taskitem_set.all().latest()[:3]
Upvotes: 30
Views: 28346
Reputation: 427
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')
Upvotes: 5
Reputation: 2360
By the way you also have Django's created_at
field at your disposal:
ordered_tasks = TaskItem.objects.order_by('-created_at')
Upvotes: 5
Reputation: 410602
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.
Upvotes: 62