views:

16

answers:

2

How to use and clause in Django

For ex:

    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")

In the above there is an error saying non-keyword arg afterkeyword arg and the error is in the above line

ipaddress is a char field,Am i constructing the query wrong if so how this should be resolved

+2  A: 
userlog.objects.filter(timestamp__range=(startdate,enddate),ipaddress !="192.168.2.211")

The use of != is not correct in Django (or indeed, not in Python). In order to exclude all records with ipaddress matching a certain value you should use the exclude() mechanism.

userlog.objects.filter(timestamp__range=(startdate,enddate)).exclude(ipaddress = 
        "192.168.2.211")
Manoj Govindan
+1  A: 

This has nothing to do with the and clause. The issue is that ipaddress !="192.168.2.211" is an invalid filter expression in Django. You can only use the equals sign in filter expressions, because they are actually keyword arguments to the filter method.

In your case, you can need to do:

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