Skip to content

Instantly share code, notes, and snippets.

@tony-albanese
Created January 12, 2023 08:27
Show Gist options
  • Save tony-albanese/e76eb416ddfb3b0667d73105c8b88579 to your computer and use it in GitHub Desktop.
Save tony-albanese/e76eb416ddfb3b0667d73105c8b88579 to your computer and use it in GitHub Desktop.
Using Q Objects
def perform_search(request):
list = request.POST.getlist('genres')
genre_query = Q()
author_query = Q()
title_query = Q()
description_query = Q()
liked_books = []
for gen in list:
genre_query = genre_query | Q(genre__iexact=gen)
title_search_terms = request.POST['title-search-input']
author_search_terms = request.POST['author-search-input']
description_search_terms = request.POST['description-search-input']
if title_search_terms:
terms = title_search_terms.split()
for term in terms:
title_query = title_query | Q(title__icontains=term)
print(title_query)
if author_search_terms:
terms = author_search_terms.split()
for term in terms:
author_query = author_query | Q(author__icontains=term)
if description_search_terms:
terms = description_search_terms.split()
for term in terms:
description_query = description_query | Q(description__icontains=term)
books = Book.objects.filter(author_query, title_query, genre_query, description_query)
for book in books:
if book.likes.filter(id=request.user.id).exists():
liked_books.append(book.id)
template = loader.get_template('index.html')
context = {
'books': books,
'liked_books': liked_books,
'heading_label': 'Search Result',
'genres': Book.GENRES
}
if request.user.is_authenticated:
return HttpResponse(template.render(context, request))
else:
return redirect('accounts/login')
@RoshnaVakkeel
Copy link

Thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment