【问题标题】:django return the most recent date of a recorddjango 返回记录的最近日期
【发布时间】:2015-01-05 02:24:48
【问题描述】:

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

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

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

我问过这个问题question on SO。

这是我的 model.py 代码:

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代码:

def get_latest_created_document_date(user):
    ??
    return latest_created_document_date

我知道我必须在用户的 get_latest_created_document_date 视图的过滤器中传递日期,但是在搜索 SO、Google 和 Django 文档之后,我仍然无法自己解决这个问题。

【问题讨论】:

    标签: python django


    【解决方案1】:

    你会想要使用order_by QuerySet filter,像这样:

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

    由于您使用的是日期字段,因此您也可以像这样使用latest filter:

    CreatedDocumentDetails.objects.latest('created_document_timestamp')
    

    如 cmets 中的双体船所述

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

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

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

    或

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

    【讨论】:

    • 请注意,如果表中没有记录,则first() 将返回None,但latest() 将引发DoesNotExist 异常。
    • Lego Stormtroopr,您对 CreatedDocumentDetails.objects.latest('created_document_timestamp') 的建议返回用户名。如何返回文档的最近创建日期?
    • 它返回整个对象,我不确定它是如何给出用户名的。不管怎样,我会更新答案。
    • Lego Stormtroopr - 谢谢,我现在明白了!这对我很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多