2014-10-17 377 views
0

我想通過日期時間過濾我的查詢。此日期時間是客戶想要了解其信息的值範圍的日期時間。我試圖將其設置到客戶選擇的月份的第一個月。我通過月份數將其轉換爲正確的字符串格式,然後轉換爲datetime對象,因爲簡單地尋找字符串對象是一個沒有返回值和Django的文件說,你需要做的是這樣的:Django過濾日期時間後,將字符串轉換爲日期時間

pub_date__gte=datetime(2005, 1, 30) 

代碼:

if 'billing-report' in request.POST: 
     customer_id = int(post_data['selected_customer']) 

這是我用得到所選客戶的日期和把它變成一個元組

if 'billing-report' in request.POST: 
    customer_id = int(post_data['selected_customer']) 
    selected_date = int(post_data['month']) 
    if selected_date < 10: 
     selected_date = '0'+str(selected_date) 
    year = datetime.now() 
    year = year.year 
    query_date = str(year) + '-' + str(selected_date) + '-01' 

    query_date_filter = datetime.strptime(query_date, "%Y-%m-%d") 


    compute_usages = ComputeUsages.objects.filter(customer_id = customer_id).filter(values_date = query_date_filter) 


django debug shows: datetime.datetime(2014, 10, 1, 0, 0) 
query_date looks like: 2014-07-01 before it is converted 

的代碼。

沒有錯誤,但沒有數據返回

我用:

compute_usages = ComputeUsages.objects.filter(customer_id = customer_id).filter(values_date = datetime(query_date_filter)) 

這是造成錯誤。我很抱歉改變我的問題,因爲它演變了,這就是爲什麼我重新包括我之前做的事情,所以這些評論是有道理的。

+0

'日期時間(..)'不是例如一個元組,'LEN()'將不起作用;它是'datetime'類的實例,例如'datetime.strptime()'類方法返回的類。嘗試將'datetime'實例傳遞給'datetime()'會產生「無效整數」錯誤:'TypeError:需要一個整數(類型爲datetime.datetime)' – jfs 2014-10-17 23:04:23

+0

謝謝@JFSebastian我只是想這樣,因爲以另一種方式傳遞不起作用。我恢復了原來的方式。但是沒有數據仍然返回。 – 2014-10-17 23:09:15

+0

可能有*多個*問題。解決這個問題並不一定能解決所有問題。不要以這樣的方式改變你的問題,例如@Daniel Roseman提供的現有答案不再有意義。 – jfs 2014-10-17 23:11:48

回答

1

花費一段時間探索查詢過濾器設置日期時間(年,月,日)後,嗯,我來到那個Django不將其轉換爲一箇中性的日期時間實現格式必須完全匹配。此外,我在數據庫中的數據有年,日,月。

學習點:

你必須使用datetime()究竟如何在數據庫Django不轉換爲中性格式和比較。我認爲這就像寫一個查詢,並說to_date或to_timestamp在哪裏數據庫將採取您的格式,並將其轉換爲中性格式與數據庫的其餘部分進行比較。

這裏是正確的方式

compute_usages = ComputeUsages.objects.filter(customer_id = customer_id).filter(values_date = datetime(year, day, selected_month)) 
1

幾乎所有的代碼都與您的問題無關。

我不明白你爲什麼打電話datetimequery_date。那就是已經是一個日期時間,就像你知道的那樣,因爲你之前把它轉換成了一個與strptime一個。所以這是不需要任何更多的轉換:

ComputeUsages.objects.filter(customer_id=customer_id).filter(values_date=query_date) 
+0

我已經嘗試過兩種方式,但另一種方式沒有返回。但是,如果我取消日期時間過濾器,它會返回所有的值,如果我查看數據庫日期時間im搜索的值存在。 – 2014-10-17 22:50:24

相關問題