Django日期查询从最新到最旧

时间:2022-09-01 17:07:45

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:

我正在从头开始构建我的第一个Django程序,并且在尝试将项目从最新到最旧打印到屏幕时遇到了麻烦。我的模型在DB中填充了自动日期时间字段,如下所示:

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]

2 个解决方案

#1


11  

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.

order_by()方法用于对查询集进行排序。它需要一个参数,即用于查询查询集的属性。使用 - 按相反顺序排序此键。

#2


0  

By the way you also have Django's created_at field at your disposal:

顺便说一句,你也可以使用Django的created_at字段:

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

#1


11  

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.

order_by()方法用于对查询集进行排序。它需要一个参数,即用于查询查询集的属性。使用 - 按相反顺序排序此键。

#2


0  

By the way you also have Django's created_at field at your disposal:

顺便说一句,你也可以使用Django的created_at字段:

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