Home > Software design >  Stringed Boolean Search or Filter in Django
Stringed Boolean Search or Filter in Django

Time:12-27

I have a user model with first_name and last_name in it.

class User(AbstractUser):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    address = models.ForeginKey(Address, on_delete=models.CASECAD, related_name='address')
    department = models.CharField(max_length=50)
    ...

And Suppose there are the data in it:

ID   first_name    last_name 
1    FightWith     Code
2    Jon           Doe
3    John          Cena

And another model with Address:

Class Address(models.Model):
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    country = models.CharField(max_length=100)
    ...

With following data in it:

ID   user    City 
4    1       Ohio
5    2       Delhi
6    3       London

I want to search them based on their fields, these fields like first_name and city/state/country or last_name and city/state/country using Boolean Search technique like following:

John AND (Ohio OR London) or (Jon OR John) AND (Delhi OR London)

Some what similar to those. I am sure we can do this using Q from django.db.models and operator module but I am not sure how.

Has anyone done this and can guide to do the same here then that would be awesome.

CodePudding user response:

If you are considering a boolean search and your query can be from multiple field, you can try django full text search queries. https://docs.djangoproject.com/en/4.1/ref/contrib/postgres/search/

CodePudding user response:

I hope this example would work in your case -

from django.db.models import Q

names = ["John", "Jane", "Joe", "Jill"]
cities = ["New York", "Dubai", "London", "Paris"]

_or_names = Q(_connector=Q.OR, *[Q(first_name=name) for name in names])
_or_city = Q(_connector=Q.OR, *[Q(address__city=city) for city in cities])

filter_exp = _or_names & _or_city

User.objects.filter(filter_exp)
  • Related