日期存储< =最近24小时时的Django返回计数 [英] Django return count when date stored <= last 24 hours

查看:30
本文介绍了日期存储< =最近24小时时的Django返回计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是菜鸟,所以这可能是一个简单的问题,但这让我很困惑.

I am noob, so this may be a simple question, but it has me stumped.

我正在创建一个测试表单,以便用户每次创建文档时,文档的创建日期和时间都将存储在CreatedDocumentDetails模型中.我尚未实现此代码,我专注于在过去24小时内返回计数.我暂时将这些值手动插入了CreatedDocumentDetails模型中.

I am creating a test form so that each time the user creates a document, the date and time the document was created will be stored in the CreatedDocumentDetails model. I have not yet implemented this code yet, I am focusing on returning the count within the last 24 hours. I have inserted the values into the CreatedDocumentDetails model manually for the time being.

问题是我要对用户在过去24小时内创建的文档进行计数.我可以返回用户保存的文档总数,但是我可以我不确定如何写现在的日期&时间字段输入到if语句中,以返回最近24小时内创建的文档数.

The issue is that I want to make a count of the documents that have been created by the user in the last 24 hours. I can return the total count of the users saved documents, but I am unsure how to write the now date & time field into the if statement to return the count of documents created in the last 24 hours.

我有以下模型:

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 the relevant views.py code:

def get_created_documents(user):
    created_documents = len(CreatedDocumentDetails.objects.filter(user=user))
    return created_documents

我假设我以某种方式将now datetime字段插入上面的get_created_documents视图代码的过滤器中.

I am assuming that I somehow insert the now datetime field into the filter of the get_created_documents view code above.

推荐答案

首先,您现有的代码非常错误.永远不要对不需要迭代的查询集进行 len :它无缘无故地获取所有数据.而是使用 count():

Firstly, your existing code is very wrong. You should never do len on a queryset that you don't otherwise need to iterate: it fetches all the data, for no reason. Instead, use count():

created_documents = CreatedDocumentDetails.objects.filter(user=user).count()

第二,由于您已经有一个条件-对用户-添加另一个条件应该不太困难.您只需要进行日期比较:

Secondly, since you already have one condition - on user - it shouldn't be too hard to add another. You just need a date comparison:

date_from = datetime.datetime.now() - datetime.timedelta(days=1)
created_documents = CreatedDocumentDetails.objects.filter(
     user=user, created_document_timestamp__gte=date_from).count()

另外,您可能会考虑重命名函数及其变量:您实际上并没有获取创建的文档,而是要对它们进行计数,因此将 count_created_documents get_created_documents_count 更好的名字.

Also you might consider renaming your function and its variables: you're not actually getting the created documents, you're counting them, so count_created_documents or get_created_documents_count would be better names.

这篇关于日期存储< =最近24小时时的Django返回计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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