Django date query from newest to oldest

I'm building my first Django program from scratch and I'm having problems trying to print items to the screen from newest to oldest. My model has an automatic date date field populated in the DB like 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 in this call:

taskitems2 = request.user.taskitem_set.all().latest()[:3]

      

+7


source to share


2 answers


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

      



The method is order_by()

used to order a set of requests. It takes one argument, an attribute by which the request will be ordered. Prefix this key using -

reverse sorting.

+14


source


By the way, you also have a Django field created_at

:



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

      

0


source







All Articles