0

我现在使用 django 过滤器来获取我想要的查询集,这是我的代码:

             students = Student.objects.filter(
                sales=current_user,
                nickname = form_data['nickname'],
                mobile = form_data['mobile'],
                gender = form_data['gender'],
                state = form_data['state'],
                source = form_data['source'],
                register_at = form_data['register_at'],
                importance = form_data['importance'],
                remaining = form_data['remaining'],
                level = form_data['level'],
                feature = form_data['feature'],
                company_name = form_data['company']
            ).order_by(register_order, remaining_order, level_order)

现在的问题是:我的一些表单数据字段可能为空,因为表单是用户输入的,他/她可以选择只输入一些字段,我想知道当某些字段为空时这段代码是否可以工作,如果不是,如何重写它以根据用户输入的字段获取查询集?

4

1 回答 1

3

逻辑可能是这样的:

# start with this
students = Student.objects.filter(sales=current_user)

value = form.cleaned_data.get('nickname', None)
if value is not None:
    students = students.filter(nickname=value)

# etc, etc ...

# end with that
students = students.order_by(register_order, remaining_order, level_order)

但是,当然,考虑到您有多少字段,这将是丑陋的。相反,你可以有这样的东西:

students = Student.objects.filter(sales=current_user)
    
fields = ['nickname', 'mobile', 'gender', ....]
for field in fields:
    value = form.cleaned_data.get(field, None)
    if value is not None:
        students = students.filter(**{field: value})
    
students = students.order_by(register_order, remaining_order, level_order)

或者,使用表单的所有字段

students = Student.objects.filter(sales=current_user)
    
for key, value in form.cleaned_data.items():
    if value is not None:
        students = students.filter(**{key: value})
    
students = students.order_by(register_order, remaining_order, level_order)

请注意,我们正在测试if value is not None而不是仅仅测试if value,这是为了允许 '0' 值通过测试。

于 2013-05-06T10:40:29.277 回答