我有4个参数:city,province,strtype,direction,当参数不为空时我想在过滤器中使用它,当它为空时,不要将其设置为过滤器关键字。
我目前使用的部分代码如下:
if (direction == '') & (strtype == '') & (city == '') & (province == ''):
queryset = address.objects.filter(addline__startswith=keyword)[:10]
if not queryset.exists():
queryset = address.objects.filter(strname__startswith=keyword)[:10]
return queryset
else:
return queryset
if (direction != '') & (strtype == '') & (city == '') & (province == ''):
queryset = address.objects.filter(addline__startswith=keyword,
strdir=direction)[:10]
if not queryset.exists():
queryset = address.objects.filter(strname__startswith=keyword,
strdir=direction)[:10]
return queryset
else:
return queryset
有16种可能,也就是说我要写16条if语句!代码太多,不优雅,有没有简洁的解决方案?
最佳答案
您可以构建字典,然后使用双星语法将其作为关键字参数传递 f(**kwargs)
:
conds = {}
if direction != '': conds["strdir"] = direction
if strtype != '': conds["strtype"] = strtype
if province != '': conds["province"] = province
if city != '': conds["city"] = city
queryset = address.objects.filter(addline__startswith=keyword,
**conds)[:10]
if not queryset.exists():
queryset = address.objects.filter(strname__startswith=keyword,
**conds)[:10]
关于python - 如何在过滤器中添加if语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050066/