django返回记录的最新日期 [英] django return the most recent date of a record

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

问题描述

我正在尝试从用户的许多记录中返回最近的日期.

I am trying to return the most recent date from a number of records by a user.

用户创建文档时,创建日期存储在CreatedDocumentDetails模型中.

When the user creates a document, the date created is stored in the CreatedDocumentDetails model.

我无法返回用户最近创建的文档的日期.

I am unable to return the date of the most recently created document by the user.

我问了关于SO的问题与该问题有关.

这是我的model.py代码:

Here is my model.py code:

class CreatedDocumentDetails(models.Model):
    user = models.ForeignKey(User)
    created_document_timestamp = models.DateTimeField(auto_now_add=True, blank=True)

    def __unicode__(self):
        return unicode(self.user)

这是我的views.py代码:

Here is my views.py code:

def get_latest_created_document_date(user):
    ??
    return latest_created_document_date

我了解我必须在用户的get_latest_created_document_date视图的过滤器中传递日期,但是在搜索SO,Google和Django文档之后,我仍然无法自行解决该问题.

I understand I have to pass the date in the filter of the get_latest_created_document_date view of the user, but after searching SO, Google and Django docs, I am still unable to figure this out on my own.

推荐答案

您将要使用

You'll want to use the order_by QuerySet filter, like so:

CreatedDocumentDetails.objects.order_by('-created_document_timestamp').first()

由于您使用的是日期字段,因此您也可以使用最新过滤器,如下所示:

Since you are using a date field, you can also use the latest filter like so:

CreatedDocumentDetails.objects.latest('created_document_timestamp')

如Catavaran在评论中所述

As catavaran states in the comments

请注意,如果表中没有记录,则 first()将返回 None ,但 latest()将引发 DoesNotExist例外

要获取日期戳,您可以将字段追加到末尾,因为两个查询都将给出一个对象:

To just get the datestamp, you can append the field to the end, as both queries will give a single object:

CreatedDocumentDetails.objects.order_by('-created_document_timestamp').first().created_document_timestamp 

CreatedDocumentDetails.objects.latest('created_document_timestamp').created_document_timestamp

这篇关于django返回记录的最新日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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