You can create a simple Search out of a ListView
:
# see search results based on user query
class SearchQuestionView(ListView):
model = Question
template_name = 'learn/search_results.html'
context_object_name = 'questions'
def get_queryset(self):
query = self.request.GET.get('q', '')
topic = self.request.GET.get('topic', '')
object_list = Question.objects.filter(
Q(question_text__icontains=query))
if topic:
object_list = object_list.filter(topic__name__icontains=topic)
return object_list
You can add additional filters in the same way you added the topic
filter.
Then, your form to search this could look like this:
<form action="{% url 'search-results' %}" method="GET">
<input name="q" type="text" placeholder="Question Text" aria-label="Search">
<input name="topic" type="text" placeholder="Topic" aria-label="Search">
<button type="submit">Search</button>
</form>
This is a cool way to get introduced to the incredibly powerful __
for Django querysets (https://docs.djangoproject.com/en/3.1/ref/models/querysets/).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…