簡體   English   中英

當存儲日期<=最后24小時時,Django返回計數

[英]Django return count when date stored <= last 24 hours

我是菜鳥,所以這可能是一個簡單的問題,但它讓我難過。

我正在創建一個測試表單,以便每次用戶創建文檔時,創建文檔的日期和時間都將存儲在CreatedDocumentDetails模型中。 我還沒有實現這個代碼,我專注於在過去24小時內返回計數。 我暫時手動將值插入到CreatedDocumentDetails模型中。

問題是我想要計算用戶在過去24小時內創建的文檔。 我可以返回用戶保存文檔的總數,但我不確定如何將現在的日期和時間字段寫入if語句以返回過去24小時內創建的文檔數。

我有以下型號:

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_created_documents(user):
    created_documents = len(CreatedDocumentDetails.objects.filter(user=user))
    return created_documents

我假設我以某種方式將now date字段插入到上面的get_created_documents視圖代碼的過濾器中。

首先,您現有的代碼是非常錯誤的。 你永遠不應該對你不需要迭代的查詢集執行len :它無緣無故地獲取所有數據。 相反,使用count()

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

其次,既然你已經有了一個條件 - 在用戶身上 - 那么添加另一個就不會太難了。 你只需要一個日期比較:

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_documentsget_created_documents_count將是更好的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM