Created
January 12, 2023 08:27
-
-
Save tony-albanese/e76eb416ddfb3b0667d73105c8b88579 to your computer and use it in GitHub Desktop.
Using Q Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for sharing!