过滤时如何在Django中同时使用AND或OR条件

时间:2019-04-24 10:21:35

标签: django filter

我想制作一个过滤器系统,如果用户同时选择年份和月份,则应显示仅属于今年月份的学生,如果用户仅选择年份,则应显示属于该年份的所有学生。如果我同时选择年份和月份但不作为OR条件,则可以使用。如何解决此问题

  

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>

     &nbsp; &nbsp;
                    <div>
                        <button type="submit" >Find Students</button>
                    </div>

      </form>

2 个答案:

答案 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,其余代码应能正常工作。