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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With