[Solved ]- Python – How do I do a not equal in Django queryset filtering?

How do I do a not equal in Django queryset filtering?

Asked on October 13, 2018 in Python.
Add Comment


  • 5 Answer(s)

    Maybe Q objects could be of help for this problem. I’ve never used them but it seems they can be negated and combined much like normal python expressions.
    Update: I Just tried it out, it seems to work pretty well:

    >>> from myapp.models import Entry
    
    from django.db.models import Q
    Entry.objects.filter(~Q(id = 3))
    [<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
    
    Answered on October 13, 2018.
    Add Comment

    Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x IS 5. I believe this will do the trick.

    results = Model.objects.filter(x=5).exclude(a=true)

    To answer your specific question, there is no “not equal to” but that’s probably because django has both “filter” and “exclude” methods available so you can always just switch the logic round to get the desired result.

     

    Answered on October 13, 2018.
    Add Comment

    The field=value syntax in queries is a shorthand for field__exact=value. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:

    exact
    
    iexact
    
    contains
    
    icontains
    
    in
    
    gt
    
    gte
    
    lt
    
    lte
    
    startswith
    
    istartswith
    
    endswith
    
    iendswith
    
    range
    
    year
    
    month
    
    day
    
    week_day
    
    isnull
    
    search
    
    regex
    
    iregex
    
    

    I’m sure by combining these with the Q objects as Dave Vogt suggests and using filter() or exclude() as Jason Baker suggests you’ll get exactly what you need for just about any possible query

    Answered on October 13, 2018.
    Add Comment

    Using exclude and filter

    results = Model.objects.filter(x=5).exclude(a=true)
    Answered on January 14, 2019.
    Add Comment

    Maybe Q objects could be of help for this problem. I’ve never used them but it seems they can be negated and combined much like normal python expressions.

    Update: I Just tried it out, it seems to work pretty well:

    >>> from myapp.models import Entry
    >>> from django.db.models import Q
    
    >>> Entry.objects.filter(~Q(id = 3))
    
    [<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, …]
    Answered on February 9, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.