2010-09-13 61 views
2

如何使用and子句中的DjangoDjango的查詢使用和條款

對於前:

select Date(timestamp) from userlog where (Date(timestamp) >= "2008-01-02" and Date(timestamp) <= "2009-01-02") and ipaddress != "192.168.2.211"; 


    Django query: 

    userlog.objects.filter(timestamp__range=(startdate,enddate),ipaddress !="192.168.2.211") 

在上面有一個錯誤,說non-keyword arg afterkeyword arg和錯誤是在上述行

ipaddress是一個字符字段,我是否構建查詢錯誤如果是這樣應該如何解決這個問題

回答

3
userlog.objects.filter(timestamp__range=(startdate,enddate),ipaddress !="192.168.2.211") 

使用!=在Django(或實際上,不在Python中)中是不正確的。爲了排除與ipaddress匹配的特定值的所有記錄,您應該使用exclude()機制。

userlog.objects.filter(timestamp__range=(startdate,enddate)).exclude(ipaddress = 
     "192.168.2.211") 
1

這與and子句無關。問題是ipaddress !="192.168.2.211"在Django中是無效的過濾器表達式。您只能使用在過濾器表達式中使用等號,因爲它們實際上是過濾器方法的關鍵字參數。

在你的情況,你可以需要做的:

userlog.objects.filter(timestamp__range=(startdate,enddate) 
        ).exclude(ipaddress="192.168.2.211")