Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django date query from newest to oldest

Tags:

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:

Model

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] 
like image 500
ryan Avatar asked May 19 '15 00:05

ryan


Video Answer


1 Answers

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.

like image 196
mipadi Avatar answered Oct 09 '22 19:10

mipadi