[Solved]-Django how to check if objects contains string in multiple fields

23👍

You can do OR queries using Q objects:

from django.db.models import Q

Puzzle.objects.filter(
    Q(title__contains=search_text) |
    Q(question__contains=search_text) |
    Q(subject__contains=search_text)
)

Of course you can build this Q object dynamically:

q = Q()
if title:
    q |= Q(title__contains=search_text)
if question:
    q |= Q(question__contains=search_text)
if subject:
    q |= Q(subject__contains=search_text)

# If you want no result if none of the fields is selected
if q:
    queryset = Puzzle.objects.filter(q)
else:
    queryset = Puzzle.objects.none()

# Or if you want all results if none of the fields is selected
queryset = Puzzle.objects.filter(q)

If you have all selected fields in a list (ie. search_fields = ['title', 'subject'], you can even make it more generic:

from functools import reduce
from operators import or_

q = reduce(or_, [Q(**{f'{f}__contains': search_text}) for f in search_fields], Q())
Puzzle.objects.filter(q)

Leave a comment