Home > Blockchain >  django filter: How to filter results with multiple values
django filter: How to filter results with multiple values

Time:10-22

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

CodePudding user response:

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

CodePudding user response:

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

Which equal to

SELECT ... WHERE name ILIKE '           
  • Related