django返回记录的最新日期 [英] django return the most recent date of a record
问题描述
我正在尝试从用户的许多记录中返回最近的日期.
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屋!