V
V
Vova1357982021-06-11 12:58:31
Django
Vova135798, 2021-06-11 12:58:31

How to search across multiple fields?

How to search across multiple fields? I found a solution like this, but it throws an error:
FieldError at /
Related Field got invalid lookup: icontains

from django.db.models import Q


def homepage(request):
    books = Book.objects.all()
    authors = Author.objects.all()
    genre = Genre.objects.all()

    search_query = request.GET.get('search', '')
    if search_query:
        books = Book.objects.filter(Q(title__icontains=search_query) | Q(genre__icontains=search_query))
    else:
        books = Book.objects.all()

    context = {
        'books': books,
        'authors': authors,
        'genre': genre,
    }
    return render(request, 'main/homepage.html', context=context)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Melnikov, 2021-06-11
@Vova135798

It seems to me that the error lies here
genre__icontains=search_query
Look towards genre__title__icontains ... Although I could be wrong.
ps since the model is genre , we don't see the title as an example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question