Rajeev
Rajeev

Reputation: 46959

django query using and clause

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

Upvotes: 2

Views: 225

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599876

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

Upvotes: 1

Manoj Govindan
Manoj Govindan

Reputation: 74765

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

Upvotes: 3

Related Questions