我正在尝试使用多个过滤器查询或不使用
technician = request.POST.get('technician')
## in the previous screen the user may not have informed the parameter, it should not be required
uniorg = request.POST.get('uniorg')
## in the previous screen the user may not have informed the parameter, it should not be required
calls = Call.objects.filter(
technician=technician,
uniorg=uniorg,
...)
我尝试过:
technician = request.POST.get('technician', '')
和
technician = request.POST.get('technician' or None)
并非所有参数都是必需的。 有人可以帮助我吗?
答案 0 :(得分:1)
最终密码
list_filters = ['type', 'technician', 'ended', 'uniorg']
filters = {k: v for k, v in request.POST.items() if k in list_filters}
for l in list_filters:
if request.POST[l] == '0' or request.POST[l] == '':
del filters[l]
calls = Call.objects.filter(start_time__gte=start_date, start_time__lte=end_date, **filters)
答案 1 :(得分:0)
您可以尝试这样的事情:
qs = Call.objects.all()
technician = request.POST.get('technician')
if technician is not None:
qs = qs.filter(technician=technician)
uniorg = request.POST.get('uniorg')
if uniorg is not None:
qs = qs.filter(uniorg=uniorg)
答案 2 :(得分:0)
一种替代方法是使用字典参数扩展:
filters = {k: v for k, v in request.POST.items() if k in ['technician', 'uniorg', ...]}
calls = Call.objects.filter(**filters)
或者,如果您确定POST中只能包含实际的有效过滤器值,则直接传递它:
calls = Call.objects.filter(**request.POST)
答案 3 :(得分:0)
您尝试过django-filter吗?这是提供GET参数过滤器的非常好工具(请注意,我不了解您的数据库设计,因此此代码可能无法正常工作)
# filters.py
class CallFilter(django_filters.FilterSet):
class Meta:
model = Call
fields = ['technician', 'uniorg',]
# view.py
items = CallFilter(request.GET, queryset=Call.objects.all())