views.py
def serachstudent(request):
year = request.GET['year']
month = request.GET['month']
if year or month:
students = Student.objects.filter(Q(joined_date__year=year) | Q(joined_date__month=month))
return render(request, "students/view_students.html", {'students': students})
elif year and month:
students = Student.objects.filter(Q(joined_date__year=year) & Q(joined_date__month=month))
return render(request, "students/view_students.html", {'students': students})
模板
<form action="{% url 'students:search_student' %}" class='form-inline'>
<!--<label for="month"></label>-->
<select name="year">
<option disabled selected>Select Year</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2019">2019</option>
</select>
<!--<label for="month"></label>-->
<select name="month">
<option disabled selected>Select month</option>
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">Decembery</option>
</select>
<div>
<button type="submit" >Find Students</button>
</div>
</form>
答案 0 :(得分:0)
if request.GET['year']: year_query = Q(joined_date__year=int(request.GET['year'])
else : year_query = Q()
if request.GET['month']: month_query = Q(joined_date__month=int(request.GET['month'])
else : month_query = Q()
query = Q(month_query | year_query)
students = Student.objects.filter(query)
答案 1 :(得分:0)
如果请求正文中未指定月份或年份,则您的代码将引发KeyError
。
更改这些行
year = request.GET['year']
month = request.GET['month']
到
year = request.GET.get('year')
month = request.GET.get('month')
这样,如果未指定它们,它们将默认为None
,其余代码应能正常工作。