Reputation: 6737
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?
Upvotes: 1
Views: 262
Reputation: 174632
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.
Upvotes: 3