我正在从头开始构建我的第一个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日期查询从最新到最旧
发布评论