如何在django中进行长查询

时间:2013-04-12 08:30:17

标签: python django

我有这个查询过滤器。但我不知道如何让它发挥作用

st = Student.objects.filter(
    if request.GET['student_number']:
        Q(student_number__icontains=request.GET['student_number'])&
    if request.GET['student_region']:
        Q(student_region__icontains=request.GET['student_region']) &
    if request.GET['student_status']:
        Q(student_status__icontains=request.GET['student_status']) &
    if request.GET['student_process']:
        Q(student_process__name__icontains=request.GET['student_process']) &

有没有更好的方法呢?

1 个答案:

答案 0 :(得分:3)

您可以像这样动态构建查询:

query_list = []
for field_name in ['student_process', 'student_status', 'student_number', 'student_region', ]:
    value = request.GET.get(field_name, None)
    if value:
        query_list.append(Q(**{field_name+'s_icontains': value}))
queryset = Student.objects.filter(reduce(operator.and_, query_list))

Here's a good blog post on the topic