1

There is the Model with some fields. I need to search some rows in the table and check multiple fields: f1,f2,f3. So, query may be matched one to three fields. For example, f1 matches, but f2 and f2 not. Or f1 and f2 matches but f3 not. And so on.

I think it should be something like this:

models_list = Model.objects.filter(f1__contains=query, 
                                   f2__contains=query, 
                                   f3__contains__query)

But how to do this condition optional and not mandatory?

Sudipta
  • 4,773
  • 2
  • 27
  • 42
Paul
  • 6,641
  • 8
  • 41
  • 56

1 Answers1

3

You need to use Q objects:

from django.db.models import Q

Model.objects.filter(
    Q(f1__contains=query) |
    Q(f2__contains=query) |
    Q(f3__contains=query)
)

If you are using MySQL, consider using search instead - it is a lot faster than contains because it uses full text indexing.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284