skip to Main Content

I am working on Django and I need to filter records eg:

table: Person

name age
David Abraham Benj 18

so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working

but if I run this, Person.objects.filter(name__icontains="David Benj") it is not working

any idea how it works?

framework: Django and SQL: Postgres

2

Answers


  1. Person.objects.filter(name__icontains="David Benj")
    

    Which equal to

    SELECT ... WHERE name ILIKE '%David Benj%';
    

    So, it doesn’t match the query. So, it’s expected behavior.

    Login or Signup to reply.
  2. You need to use Q objects in order to chain multiple SQL ILIKE operations, which is what the __icontains operator produces in the backgroud.

    Try this:

    from django.db.models import Q
    
    Person.objects.filter(
        Q(name__icontains="David") &
        Q(name__icontains="Benj")
    )
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search