Django日期查询从最新到最旧

编程入门 行业动态 更新时间:2024-10-24 03:21:39
本文介绍了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日期查询从最新到最旧

本文发布于:2023-10-27 23:31:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534852.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:新到   日期   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!