我正在嘗試使用對應於不同數據段的三個字段搜索模型對象的搜索頁。這裏是我下面的代碼:在Django中進行多字段搜索
models.py
class Schedules(models.Model):
course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
views.py
def search_Schedule(request):
context_dict = {}
if request.method == 'POST':
query1 = request.POST['course_name_search']
query2 = request.POST['start_date_search']
query3 = request.POST['instructor_search']
if query1:
results = Schedules.objects.filter(course_name__icontains=query1)
if query2:
results = results.filter(start_time=query2)
if query3:
results = results.filter(instructor__icontains=query3)
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
else:
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query1 + " and " + query2
elif query3:
results = results.filter(start_time__icontains=query3)
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query1 + " and " + query3
else:
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query1
elif query2:
results = Schedules.objects.filter(start_time=query2)
if query3:
results = results.filter(instructor__icontains=query3)
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query2 + " and " + query3
else:
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query2
elif query3:
results = Schedules.objects.filter(instructor__icontains=query3)
table = ScheduleTable(results)
if results.count():
context_dict['table'] = table
else:
context_dict['no_results'] = query3
return render(request, "schedule/search_schedule.html", context_dict)
search_schedule.html
{% block main_content %}
<form method="post" action="">
{% csrf_token %}
<label for="course_name_search">Course Name:</label>
<input type="text" name="course_name_search" id="course_name_search">
<label for="start_date_search">Start Date:</label>
<input type="datetime" name="start_date_search" id="start_date_search">
<label for="instructor_search">Instructor:</label>
<input type="text" name="instructor_search" id="instructor_search"><br>
<input type="submit" name="submit">
</form>
<div id="result_panel">
{% if table %}
{% render_table table %}
{% else %}
{% if no_results %}
No results returned for <q>{{ no_results }}</q>
{% else %}
Please enter a search
{% endif %}
{% endif %}
{% endblock %}
出於某種原因,搜索將工作,如果我輸入課程名稱字段或教師字段,但如果我輸入多個字段則不起作用。由於某種原因,無論我如何輸入日期,開始日期字段都不會工作。有人可以幫我用正確的方式輸入代碼嗎?謝謝。
沒關係,我設法解決它。好像我在字段中輸入錯誤的東西。 –