python - 如何在过滤器中添加if语句?

标签 python django

我有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/

相关文章:

python - 如何在 AWS lambda 函数中从 S3 访问 css/js 文件

带有网络摄像头的 Python 2.7 CV2 和 Tkinter

python - Python 中的 x.type 和 type(x) 有什么区别?

python - 由于南方模式迁移的顺序,我的 Django 测试无法正常工作?

sql - Django Raw SQL给我TypeError没有足够的参数

Python Azure GetSharedAccessSignature

python - 如何在 CreateView 的 form_valid 方法中引发错误

python - 防止为特定的 save() 调用发送信号

python - Docker-compose 无法导入 Django (ModuleNotFoundError)

django - 如何将类属性添加到 Django 身份验证登录表单?