Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

398
Visualizações
How to implement my own search filter - Django?

I have a Book model:

class Book(models.Model):
    title = models.CharField()
    ...

HTML form:

<form type="get" action=".">
    <input id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button type="submit" >Submit</button>
</form>

For example: User input some text in my form:"Some strange text" I wanna find all books, which contain at least one of these words in upper or lower case or some phrases in this text('Some', 'some', 'Strange', 'strange', 'Text', 'text' or 'some strange', 'Strange text' and so on). How can I do that?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can split the search query to obtain the words, and then match these with the title of the book. We can do this by constructing a Q object [Django-doc] that will represent the filter condition:

from django.db.models import Q

query = request.GET.get('search_box')
books = Book.objects.all()
if query:
    query = query.split()
    q_obj = Q(
        *[Q(('title__icontains', item)) for item in query],
        _connector=Q.OR
    )
    books = Book.objects.filter(q_obj)

If the search box is filled in, it will filter the books queryset, such that it contains at least one word of the query.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda