Django日期查询从最新到最旧 [英] Django date query from newest to oldest

查看:105
本文介绍了Django日期查询从最新到最旧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

想在此调用中实现它:

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


推荐答案

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

order_by() 方法用于对查询集进行排序。它采用一个参数,即查询集排序所依据的属性。在此键之前加上-会以相反的顺序排序。

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.

这篇关于Django日期查询从最新到最旧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆